<?php

/**
 * @Author:      zwh
 * @DateTime:    2016-1-15 10:21:01
 * @Description: 用于订单信息变更的操作
 */
class ScsOrderChangeController extends BaseController
{
    /**
     * @Author:      zwh
     * @DateTime:    2016-01-06 13:43:32
     * @Description: 修改订单中用户信息
     */
    public function update_order_user_info(){
    	$validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'order_id' => 'required',
                'name' => 'required',
                'phone' => 'required',
                'sex' => 'required'
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
    	do{
    		if($validator->fails()) {
    		    $messages = $validator->messages();
    		    if($messages->has('number')){
    		        $response = Lang::get("scs_error.args_error_10004");
    		        $response["result"]=$validator->messages()->all();
    		        break;
    		    }
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $orders=Orders::find(Input::get('order_id'));
            if(is_null($orders)||$orders->order_type!=1){
                $response = Lang::get("scs_error.order_notexiet_40000");
                break;
            }
            if($orders->shop_id!=$sc_user->shop_id){
                $response = Lang::get("scs_error.order_note_shop_error_40003");
                break;

            }
            /*
            $uci=UserCarInfo::find($orders->user_car_id);
            if(is_null($uci)){
                $response = Lang::get("scs_error.order_car_info_notexit_40001");
                break;
            }

            $csi=DataCarStandardInfo::find($uci->car_model_id);
            if(is_null($csi)){
                $response = Lang::get("scs_error.order_car_model_notexit_40002");
                break;
            }
            */
            if(in_array($orders->status,array(1010, 1110, 1210, 1310, 1410,1018,1117, 1217, 1417, 1420,1219, 1419))){
                $response = Lang::get("scs_error.order_status_error_40005");
                break;

            }
            if(Input::get('sex')==1){
                $tittle='先生';
            }elseif(Input::get('sex')==2){
                $tittle='女士';
            }else{
                $tittle='保密';
            }
            //记录订单基本信息修改记录
            $obmr = new OrderBaseModifyRecord();
            $obmr->order_id=Input::get("order_id");
            $obmr->tittle=$orders->tittle;
            $obmr->name=$orders->name;
            $obmr->phone=$orders->phone;
            $obmr->mileage=$orders->mileage;
            $obmr->oil_meter=$orders->oil_meter;
            $obmr->address=$orders->address;
            $obmr->product_comment=$orders->product_comment;
            $obmr->car_brand_id=$orders->car_brand_id;
            $obmr->car_brand_name=$orders->car_brand_name;
            $obmr->car_series_id=$orders->car_series_id;
            $obmr->car_series_name=$orders->car_series_name;
            $obmr->car_model_id=$orders->car_model_id;
            $obmr->car_model_name=$orders->car_model_name;
            $obmr->user_id=$sc_user->id;
            $obmr->user_type='sc';
            $obmr->save();

            $orders->phone=Input::get('phone');
            $orders->name=Input::get('name');
            $orders->tittle=$tittle;
            $orders->save();
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("order_id"=>Input::get('order_id')));
    	}while(false);
    	Log::info("info", array("system" => "scs" ,"event" => "order_show", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /**
     * @Author:      zwh
     * @DateTime:    2016-1-15 10:22:38
     * @Description: 修改订单车型信息
     */
    public function update_order_car_model(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                //'car_no'=>'required|max:20|alpha_dash',
                'car_model_id'=>'required|max:20|alpha_dash',
                "mileage"=>'required|numeric',
                "vin"=>'required',
                "note"=>'max:100',
                'order_id' => 'required'
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $csi=DataCarStandardInfo::find(Input::get("car_model_id"));
            if(is_null($csi)){
                $response = Lang::get("scs_error.order_car_model_notexit_40002");
                break;
            }
            $orders=Orders::find(Input::get('order_id'));
            if(is_null($orders)||$orders->order_type!=1){
                $response = Lang::get("scs_error.order_notexiet_40000");
                break;
            }
            if($orders->shop_id!=$sc_user->shop_id){
                $response = Lang::get("scs_error.order_note_shop_error_40003");
                break;

            }
            if(in_array($orders->status,array(1010, 1110, 1210, 1310, 1410,1018,1117, 1217, 1417, 1420,1219, 1419))){
                $response = Lang::get("scs_error.order_status_error_40005");
                break;

            }
            $uci=UserCarInfo::where('id',$orders->user_car_id)->where("status",1)->first();
            if(is_null($uci)){
                $uci=UserCarInfo::where('user_id',$orders->user_id)->where('car_no',strtoupper($orders->car_no))->where("status",1)->first();
                if(is_null($uci)){
                    $uci=new UserCarInfo;
                    $uci->car_no = strtoupper($orders->car_no);
                    $uci->user_id = $orders->user_id;
                    $uci->status = 1;
                    $uci->is_default = 0;
                    $uci->car_level = 0;
                    $uci->is_lock = 0;
                    $uci->mileage =0;//
                }                
            }
            // if(Input::get('mileage')<$uci->mileage){//如果 这次保养的里程 小于
            //     $response = Lang::get("scs_error.order_mileage_error_40030");
            //     break;
            // }
            if($uci->is_lock==1){//如果是认证车辆
                //修改其他车型不同的的认证车辆 认证状态为未认证
                UserCarInfo::where("car_no",$uci->car_no)->where("is_lock",1)->where("car_model_id","!=",$csi->id)->update(array("is_lock"=>0));
                UserCarInfo::where("id",$uci->id)->update(array("is_lock"=>1));
                // $uci->is_lock=1;
                // $uci->save();
                $uacs=UserAuthenticationCar::where('car_no',$uci->car_no)->where('car_model_id',$csi->id)->where('status',1)->get();
                if(!sizeof($uacs)){
                    UserAuthenticationCar::where("car_no",$uci->car_no)->update(array("status"=>0));
                    $uac=new UserAuthenticationCar();
                    $uac->status=1;
                    $uac->car_no=$uci->car_no;
                    $uac->vin_code=strtoupper(Input::get("vin"));
                    $uac->mileage=$uci->mileage;
                    $uac->car_brand_id=$csi->brand_name_id;
                    $uac->car_series_id=$csi->series_name_id;
                    $uac->car_model_id=$csi->id;
                    $uac->user_id=$uci->user_id;
                    $uac->shop_id=$sc_user->shop_id;
                    $uac->create_by=$sc_user->id;
                    $uac->shop_id=$sc_user->shop_id;
                    $uac->save();
                }
            }
    
            // $uci=UserCarInfo::find($orders->user_car_id);
            $uci->car_series_id = $csi->series_name_id;
            $uci->car_brand_id = $csi->brand_name_id;
            $uci->car_model_id = $csi->id;
            $uci->vin_code = strtoupper(Input::get("vin"));
            // $uci->mileage =Input::get('mileage')?Input::get('mileage'):0;
            $uci->note=Input::get("note");
            //$uci->car_no=Input::get("car_no");
            $uci->insurance=Input::get('insurance');
            $uci->start_off_time=Input::get('start_off_time');
            $uci->save();
            //记录订单基本信息修改记录
            $obmr = new OrderBaseModifyRecord();
            $obmr->order_id=Input::get("order_id");
            $obmr->name=$orders->name;
            $obmr->phone=$orders->phone;
            $obmr->mileage=$orders->mileage;
            $obmr->oil_meter=$orders->oil_meter;
            $obmr->address=$orders->address;
            $obmr->product_comment=$orders->product_comment;
            $obmr->car_brand_id=$orders->car_brand_id;
            $obmr->car_brand_name=$orders->car_brand_name;
            $obmr->car_series_id=$orders->car_series_id;
            $obmr->car_series_name=$orders->car_series_name;
            $obmr->car_model_id=$orders->car_model_id;
            $obmr->car_model_name=$orders->car_model_name;
            $obmr->user_id=$sc_user->id;
            $obmr->user_type='sc';
            $obmr->save();

            $orders->note = Input::get("note","");
            $orders->car_brand_id = $csi->brand_name_id;
            $orders->car_brand_name = $csi->brand_name;
            $orders->car_series_id = $csi->series_name_id;
            $orders->car_series_name = $csi->series_name;
            $orders->car_model_id = $csi->id;
            $orders->car_model_name = $csi->model_name;
            //$orders->car_no = Input::get('car_no');
            $orders->mileage = Input::get('mileage');
            $orders->user_car_id = $uci->id;
            $orders->save();
            MaintenanceStationCarStatus::update_station_info(Input::get("order_id"),Input::get("car_model_id"),strtoupper(Input::get("vin","")),Input::get('mileage'),Input::get("insurance"),Input::get('start_off_time'));

            // $order_flows = new OrderFlows;
            // $order_flows->order_id = Input::get('order_id');
            // $order_flows->status =1411;
            // $order_flows->user_id = $sc_user->id;
            // $order_flows->type = 'sc';
            // $order_flows->save();
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("order_id"=>Input::get('order_id')));
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "order_create", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /**
     * @Author:      lyt
     * @DateTime:  2017-07-04 14:07:47
     * @Description: 订单中更新车辆行驶证信息
     */
    public function update_driving_license(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'vin_code'=>'required',
                "send_time"=>'required',
                'order_id' => 'required'
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }            
            $orders=Orders::find(Input::get('order_id'));
            if(is_null($orders)){
                $response = Lang::get("scs_error.order_notexiet_40000");
                break;
            }
            if($orders->shop_id!=$sc_user->shop_id){
                $response = Lang::get("scs_error.order_note_shop_error_40003");
                break;
            }
            if(in_array($orders->status,array(1010, 1110, 1210, 1310, 1410,1018,1117, 1217, 1417, 1420,1219, 1419))){
                $response = Lang::get("scs_error.order_status_error_40005");
                break;
            }
            if($orders->car_no==""||$orders->user_car_id==0){
                $response = Lang::get("scs_error.order_car_no_error_40125");
                break;
            }
            $uci=UserCarInfo::find($orders->user_car_id);       
            if($uci->is_lock==1){//如果是认证车辆                
                UserAuthenticationCar::where('car_no',$uci->car_no)->where('status',1)->update(array("vin_code"=>strtoupper(Input::get("vin_code"))));
            }            
            $uci->vin_code = strtoupper(Input::get("vin_code"));
            if(Input::get('register_time')){
                $uci->start_off_time=Input::get('register_time');
            }           
            $uci->save();            

            $dln=DrivingLicenseNew::where("car_no",$uci->car_no)->where("vin",Input::get('vin_code'))->where("send_time",Input::get('send_time'))->first();
            if(is_null($dln)){//如果没有新建改记录
                $dln=new DrivingLicenseNew();
                $dln->shop_id = $sc_user->shop_id;
                $dln->created_by=$sc_user->id;
            }else{
                $dln->updated_by=$sc_user->id;
            }
            if(Input::get('img')!="null"){
                $dln->img = Input::get('img');
            }
            $dln->car_no = $uci->car_no;
            $dln->car_type = Input::get('car_type');
            $dln->own = Input::get('own');
            $dln->address = Input::get('address');
            $dln->model = Input::get('model');
            $dln->vin = strtoupper(Input::get("vin_code"));
            $dln->engine_number = Input::get('engine_number');
            $dln->register_time = Input::get('register_time');
            $dln->send_time = Input::get('send_time');
            $dln->use_nature = Input::get('use_nature');
            $dln->updated_at = Common::currentTimeString();
            if (empty($dln->is_lock)){ //$dln->is_lock == 1 锁定不允许修改
                $dln->save();
            }
            $dlo=DrivingLicenseOrder::where("license_id",$dln->id)->where("order_id",$orders->order_id)->first();
            if(is_null($dlo)){
                $dlo=new DrivingLicenseOrder();
                $dlo->order_id=$orders->order_id;
                $dlo->license_id=$dln->id;
                $dlo->created_by=$sc_user->id;
                $dlo->save();
            }            
            // $dls=DrivingLicenseShop::where("license_id",$dln->id)->where("shop_id",$sc_user->shop_id)->first();
            // if(is_null($dls)){
            $dls=new DrivingLicenseShop();
            $dls->license_id=$dln->id;
            $dls->shop_id=$sc_user->shop_id;
            $dls->created_by=$sc_user->id;
            $dls->save();
            // }
            // $dlu=DrivingLicenseUser::where("license_id",$dln->id)->where("user_id",$orders->user_id)->first();
            // if(is_null($dlu)){
            $dlu=new DrivingLicenseUser();
            $dlu->license_id=$dln->id;
            $dlu->user_id=$orders->user_id;
            $dlu->created_by=$sc_user->id;
            $dlu->save();
            // }            
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("order_id"=>Input::get('order_id')));
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "update_driving_license", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /**
     * @Author:      zwh
     * @DateTime:    2016-1-15 13:42:38
     * @Description: 修改订单产品信息
     */
    public function updateOrderProductItems(){

    }


    /**
     * @Author:      lyt
     * @DateTime:    2016-01-19 10:58:21
     * @Description: 用于添加 订单的产品项
     */
    public function addProduct(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'order_id'=>'required',
                "pack_id"=>'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $orders=Orders::find(Input::get('order_id'));
            if(is_null($orders)){
                $response = Lang::get("scs_error.order_notexiet_40000");
                break;
            }
            if($orders->shop_id!=$sc_user->shop_id){
                $response = Lang::get("scs_error.order_note_shop_error_40003");
                break;
            }
            if($orders->order_type==1){
                if(!in_array($orders->status,Orders::$add_product)){//订单状态是正确
                    $response = Lang::get("scs_error.order_status_error_40022");
                    break;
                }
            }else{
                if($orders->status!=1411){//订单状态是正确
                    $response = Lang::get("scs_error.order_status_error_40022");
                    break;
                }
            }
            $op=OrderPay::where("order_id",$orders->order_id)->whereIn("status",array(0,1,5,7))->first();      
            if($op){//订单状态是否为服务结束状态
                $response = Lang::get("scs_error.order_pay_record_40112");
                break;
            }  
            $op=OrderPerformance::where('order_id',Input::get("order_id"))->first();
            if($op){//如果存在检测记录
                if(date("Y-m",strtotime($op->created_at))!=date("Y-m",time())){
                    $response = Lang::get("scs_error.order_checek_time_error_40079");
                    break;
                }
            }


            $csi=DataCarStandardInfo::find($orders->car_model_id);
            if(is_null($csi)){
                $response = Lang::get("scs_error.car_model_is_empty23000");
                break;
            }
            $package=ProductPackage::find(Input::get("pack_id"));
            if(is_null($package)){
                $response = Lang::get("scs_error.package_error_50001");
                break;
            }
            if($package->status!=1){
                $response = Lang::get("scs_error.package_status_error_50002");
                break;
            }
            // $ppc=ProductPackageCity::where("city_id",$orders->city)->where("status",1)->where("pack_id",$package->id)->first();
            $ppc=ProductPackageShop::isShopPackage($orders->shop_id,$package->id);
            if(!$ppc){
                $response = Lang::get("scs_error.package_unable_error_50003");
                break;
            }
            // if($package->city!=$sc_user->shop->city_id){
            //     $response = Lang::get("scs_error.package_unable_error_50003");
            //     break;
            // }
            $p_item=ProductPackage::getItem($orders->car_model_id,$package->id);
            $whp=WorkHoursPrice::where("city_id",$sc_user->shop->city_id)->first();
            if(is_null($whp)){
                $response = Lang::get("scs_error.work_hour_error_10001");
                break;
            }
            $wmcf=WorkModelCoefficient::where("name",$csi->model_level)->first();
            if(is_null($wmcf)){
                $response = Lang::get("scs_error.work_mcf_error_10002");
                break;
            }
            $count_amount=0;
            $supply_arr=$p_item['supply'];
            $order_product_item=array();
            foreach ($supply_arr as $_sa) {
                //更换耗材的加价系数
                $wpc=WorkPartsCoefficient::where("car_model_name",$csi->model_level)->where("supply_brand_id",$_sa["brand_id"])->where("supply_subject_id",$_sa["subject"])->where("status",1)->first();
                $wmcf->supply_coefficient = null;
                if (!empty($wpc)) {
                    $wpc_city=WorkPartsCoefficientCity::where('city_id',$sc_user->shop->city_id)->where('coefficient_id',$wpc->id)->where('status',1)->first();
                    $wmcf->supply_coefficient=isset($wpc_city->coefficient) ? $wpc_city->coefficient : null; //如果有城市系数，优先使用。
                }
                if ($wmcf->supply_coefficient == null){ //如果是0，说明没有赋值
                    $wmcf->supply_coefficient=isset($wpc->coefficient) ? $wpc->coefficient : 1;
                }
                //更换多城市价格
                // $sip=SupplyItemPrice::where("item_id",$_sa["id"])->where("city_id",$sc_user->shop->city_id)->first();
                // if($sip){
                //     $_sa["amount"]=$sip->price;
                // }

                $sip=SupplyCityPrice::where("supply_id",$_sa["id"])->where("city_id",$orders->city)->where("status",1)->first();
                if($sip){
                    $_sa["amount"]=$sip->price;
                }else{
                    $ss_temp=SupplySub::where("supply_id",$_sa["id"])->where("status",1)->first();
                    $_sa["amount"]=isset($ss_temp)?$ss_temp->usual_price:0;
                }
                // $c_amount=Common::upFow($si->amount*$wmcf->supply_coefficient);

                $temp_amount=$_sa["amount"]*$wmcf->supply_coefficient;
                $temp_amount=Common::upFow($temp_amount);
                $order_product_item[]=array(
                    "item_id"=>$_sa["id"],
                    "item_name"=>$_sa["name"],
                    "amount"=>$temp_amount,
                    "num"=>$_sa["number"],
                    "type"=>1,
                    "unit"=>$_sa["unit"],
                    "is_adapter"=>$_sa["is_adapter"],
                );
                $count_amount+=$temp_amount*$_sa["number"];
            }
            foreach ($p_item['server'] as $_se) {
                $res=PricingStrategy::getStringStrategy($csi->id,$_se['id'],$sc_user->shop->city_id);
                if($res['code']==0){
                    $temp_amount=$res['price'];
                }else{
                    //判断工时类型为工时类型还是固定价格
                    if($_se['type'] ==1 ){
                        $temp_amount=$whp->price*$wmcf->work_coefficient*$_se["work_hours"];
                    }elseif($_se['type']==2){
                        $temp_amount=$_se["price"];
                    }
                }
                $order_product_item[]=array(
                    "item_id"=>$_se["id"],
                    "item_name"=>$_se["name"],
                    "amount"=>$temp_amount,
                    "num"=>$_se["work_hours"],
                    "type"=>2,
                    "unit"=>"个",
                    "is_adapter"=>1,
                );
                $count_amount+=$temp_amount;
            }
            $package_arr=array(array(
                "product_id"=>$package->id,
                "product_name"=>$package->name,
                "amount"=>$count_amount,
                "item"=>$order_product_item
            ));
            OrderProduct::saveBaseProducts($package_arr,"",$sc_user->id,$orders->order_id);
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("order_id"=>Input::get('order_id')));
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "addProduct", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /**
     * @Author:      zwh
     * @DateTime:    2016-1-20 16:36:34
     * @Description: 用于添加 订单的产品项（多个）
     */
    public function addProducts(){
        $validator = Validator::make(Input::all(),
            array(
                'token'    => 'required',
                'order_id' => 'required',
                "pack_id"  => 'required',
            )
            );
        $success = array();
        $response = array('code' => 0, 'msg' => 'ok','result'=>array('order_id'=>Input::get('order_id')));
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $orders=Orders::find(Input::get('order_id'));
            if(is_null($orders)){
                $response = Lang::get("scs_error.order_notexiet_40000");
                break;
            }
            if($orders->shop_id!=$sc_user->shop_id){
                $response = Lang::get("scs_error.order_note_shop_error_40003");
                break;
            }
            if($orders->order_type==1){
                if(!in_array($orders->status,Orders::$add_product)){//订单状态是正确
                    $response = Lang::get("scs_error.order_status_error_40022");
                    break;
                }
            }else{
                if($orders->status!=1411){//订单状态是正确
                    $response = Lang::get("scs_error.order_status_error_40022");
                    break;
                }
            }
            $op=OrderPay::where("order_id",$orders->order_id)->whereIn("status",array(0,1,5,7))->first();      
            if($op){//订单状态是否为服务结束状态
                $response = Lang::get("scs_error.order_pay_record_40112");
                break;
            } 
            $csi=DataCarStandardInfo::find($orders->car_model_id);
            if(is_null($csi)){
                $response = Lang::get("scs_error.car_model_is_empty23000");
                break;
            }
            $pack_id = json_decode(Input::get('pack_id'),1);

            $whp=WorkHoursPrice::where("city_id",$sc_user->shop->city_id)->first();
            if(is_null($whp)){
                $response = Lang::get("scs_error.work_hour_error_10001");
                break;
            }
            $wmcf=WorkModelCoefficient::where("name",$csi->model_level)->first();
            if(is_null($wmcf)){
                $response = Lang::get("scs_error.work_mcf_error_10002");
                break;
            }


            //循环添加产品包
            foreach($pack_id as $pi){
                $package=ProductPackage::find($pi);
                if(is_null($package)){
                    $response = Lang::get("scs_error.package_error_50001");
                    break;
                }
                if($package->status!=1){
                    $response = Lang::get("scs_error.package_status_error_50002");
                    break;
                }
                // $ppc=ProductPackageCity::where("city_id",$orders->city)->where("status",1)->where("pack_id",$package->id)->first();
                $ppc=ProductPackageShop::isShopPackage($orders->shop_id,$package->id);
                if(!$ppc){
                    $response = Lang::get("scs_error.package_unable_error_50003");
                    break;
                }
                // if($package->city!=$sc_user->shop->city_id){
                //     $response = Lang::get("scs_error.package_unable_error_50003");
                //     break;
                // }
                $p_item=ProductPackage::getItem($orders->car_model_id,$package->id);
                if(sizeof($p_item["not_pin"])>0){//说明是存在没有匹配上的的耗材
                    continue;
                }
                $count_amount=0;
                $supply_arr=$p_item['supply'];
                $order_product_item=array();
                foreach ($supply_arr as $_sa) {
                    //更换耗材的加价系数
                    $wpc=WorkPartsCoefficient::where("car_model_name",$csi->model_level)->where("supply_brand_id",$_sa["brand_id"])->where("supply_subject_id",$_sa["subject"])->where("status",1)->first();
                    $wmcf->supply_coefficient = null;
                    if (!empty($wpc)) {
                        $wpc_city=WorkPartsCoefficientCity::where('city_id',$sc_user->shop->city_id)->where('coefficient_id',$wpc->id)->where('status',1)->first();
                        $wmcf->supply_coefficient=isset($wpc_city->coefficient) ? $wpc_city->coefficient : null; //如果有城市系数，优先使用。
                    }
                    if ($wmcf->supply_coefficient == null){ //如果是0，说明没有赋值
                        $wmcf->supply_coefficient=isset($wpc->coefficient) ? $wpc->coefficient : 1;
                    }
                    //更换多城市价格
                    // $sip=SupplyItemPrice::where("item_id",$_sa["id"])->where("city_id",$orders->city)->first();
                    // if($sip){
                    //     $_sa["amount"]=$sip->price;
                    // }
                    $sip=SupplyCityPrice::where("supply_id",$_sa["id"])->where("city_id",$orders->city)->where("status",1)->first();
                    if($sip){
                        $_sa["amount"]=$sip->price;
                    }else{
                        $ss_temp=SupplySub::where("supply_id",$_sa["id"])->where("status",1)->first();
                        $_sa["amount"]=isset($ss_temp)?$ss_temp->usual_price:0;
                    }

                    $temp_amount=$_sa["amount"]*$wmcf->supply_coefficient;
                    $temp_amount=Common::upFow($temp_amount);
                    $order_product_item[]=array(
                        "item_id"=>$_sa["id"],
                        "item_name"=>$_sa["name"],
                        "amount"=>$temp_amount,
                        "num"=>$_sa["number"],
                        "type"=>1,
                        "unit"=>$_sa["unit"],
                    );
                    $count_amount+=$temp_amount*$_sa["number"];
                }
                foreach ($p_item['server'] as $_se) {
                    $res=PricingStrategy::getStringStrategy($csi->id,$_se['id'],$sc_user->shop->city_id);
                    if($res['code']==0){
                        $temp_amount=$res['price'];
                    }else{
                        //判断工时类型为工时类型还是固定价格
                        if($_se['type'] ==1 ){
                            $temp_amount=$whp->price*$wmcf->work_coefficient*$_se["work_hours"];
                        }elseif($_se['type']==2){
                            $temp_amount=$_se["price"];
                        }
                    }
                    $order_product_item[]=array(
                        "item_id"=>$_se["id"],
                        "item_name"=>$_se["name"],
                        "amount"=>$temp_amount,
                        "num"=>$_se["work_hours"],
                        "type"=>2,
                        "unit"=>"个",
                    );
                    $count_amount+=$temp_amount;
                }
                $package_arr=array(array(
                    "product_id"=>$package->id,
                    "product_name"=>$package->name,
                    "amount"=>$count_amount,
                    "item"=>$order_product_item
                ));
                OrderProduct::saveBaseProducts($package_arr,"",$sc_user->id,$orders->order_id);
                $success[]=array('pack_id'=>$package->id,'pack_name'=>$package->name);
            }
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "addProduct", 'input' =>Input::all() ,"output" => $response));
        $response['success']=$success;
        return json_encode($response);
    }

    /**
     * @Author:      zwh
     * @DateTime:    2016-1-21 16:10:21
     * @Description: 根据耗材品类id提供产品包
     */
    public function getProductPackages(){
        $validator = Validator::make(Input::all(),
            array(
                'token'    => 'required',
                //'order_id' => 'required',
                "subject_ids"  => 'required',
                'car_model_id' => 'required'
            )
            );
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            //$orders=Orders::find(Input::get('order_id'));
            //if(is_null($orders) || $orders->order_type==2){
            //   $response = Lang::get("scs_error.order_notexiet_40000");
            ///   break;
            //}
            //if($orders->shop_id!=$sc_user->shop_id){
            //    $response = Lang::get("scs_error.order_note_shop_error_40003");
            //    break;
            //}
            $csi=DataCarStandardInfo::find(Input::get('car_model_id'));
            if(is_null($csi)){
                $response = Lang::get("scs_error.order_car_model_notexit_40002");
                break;
            }
            $whp=WorkHoursPrice::where("city_id",$sc_user->shop->city_id)->first();
            if(is_null($whp)){
                $response = Lang::get("scs_error.work_hour_error_10001");
                break;
            }
            $wmcf=WorkModelCoefficient::where("name",$csi->model_level)->first();
            if(is_null($wmcf)){
                $response = Lang::get("scs_error.work_mcf_error_10002");
                break;
            }

            $subject_ids = json_decode(Input::get('subject_ids'));
            $pack_arr=ProductPackage::helpDecodeShop($subject_ids,$sc_user->shop_id);
            if(isset($pack_arr['not_pi'])){
                $not_pin=$pack_arr['not_pi'];
                unset($pack_arr['not_pi']);
            }
            $arr1=$np=array();
            //由产品包和车型获取符合条件的包
            foreach($pack_arr as $key=>$pack){
                $p_item=ProductPackage::getItem(Input::get('car_model_id'),$key);
                //产品包如果有一个没有匹配上则过滤

                if(!empty($p_item['not_pin'])){
                    foreach($pack['own'] as $p){
                        $not_pin[] = $p;
                    }
                    unset($pack_arr[$key]);
                }else{
                    //某个产品包全部匹配上耗材，则not_pin数组为空可unset
                    unset($p_item['not_pin']);
                    $count_amount=0;
                    $supply_arr=$p_item['supply'];
                    $order_product_item=array();
                    foreach ($supply_arr as &$_sa) {
                        $item_info=SupplyItem::getCacheItemInfo($_sa["id"]);
                        //更换耗材的加价系数
                        $wpc=WorkPartsCoefficient::where("car_model_name",$csi->model_level)->where("supply_brand_id",$_sa["brand_id"])->where("supply_subject_id",$_sa["subject"])->where("status",1)->first();
                        $wmcf->supply_coefficient = null;
                        if (!empty($wpc)) {
                            $wpc_city=WorkPartsCoefficientCity::where('city_id',$sc_user->shop->city_id)->where('coefficient_id',$wpc->id)->where('status',1)->first();
                            $wmcf->supply_coefficient=isset($wpc_city->coefficient) ? $wpc_city->coefficient : null; //如果有城市系数，优先使用。
                        }
                        if ($wmcf->supply_coefficient == null){ //如果是0，说明没有赋值
                            $wmcf->supply_coefficient=isset($wpc->coefficient) ? $wpc->coefficient : 1;
                        }
                        //更换多城市价格
                        // $sip=SupplyItemPrice::where("item_id",$_sa["id"])->where("city_id",$sc_user->shop->city_id)->first();
                        // if($sip){
                        //     $_sa["amount"]=$sip->price;
                        // }
                        $sip=SupplyCityPrice::where("supply_id",$_sa["id"])->where("city_id",$sc_user->shop->city_id)->where("status",1)->first();
                        if($sip){
                            $_sa["amount"]=$sip->price;
                        }else{
                            $ss_temp=SupplySub::where("supply_id",$_sa["id"])->where("status",1)->first();
                            $_sa["amount"]=isset($ss_temp)?$ss_temp->usual_price:0;
                        }

                        $temp_amount=$_sa["amount"]*$wmcf->supply_coefficient;
                        $temp_amount=Common::upFow($temp_amount);
                        $_sa["amount"]=$temp_amount;
                        $_sa["scf_id"]=$item_info->scf_id;
                        $_sa["scf_name"]=$item_info->scf_name;
                        $_sa["specification"]=$item_info->specification;
                        $count_amount+=$temp_amount*$_sa["number"];
                    }
                    foreach ($p_item['server'] as $_se) {
                        $temp_amount=$whp->price*$wmcf->work_coefficient*$_se["work_hours"];
                        $order_product_item[]=array(
                            "item_id"=>$_se["id"],
                            "item_name"=>$_se["name"],
                            "amount"=>$temp_amount,
                            "num"=>$_se["work_hours"],
                            "type"=>2,
                            "unit"=>"个",
                        );
                        $count_amount+=$temp_amount;
                    }
                    $arr['pack_id']=$key;
                    $pp=ProductPackage::find($key);
                    $arr['pack_name']=$pp->name;
                    $arr['amount']=$count_amount;
                    $arr['items']=array("supply"=>$supply_arr,"server"=>$order_product_item);
                    $arr1[]=$arr;
                }
            }
            $packages['packages']=$arr1;
            $np=array();
            if(!empty($not_pin)){
                foreach($not_pin as $sub){
                    $ss=SupplyClassification::find($sub);
                    $arr2['id']=$sub;
                    $arr2['name']=$ss->name;
                    $np[]=$arr2;

                }
            }
            $packages['not_pin']=$np;
            $response = array('code' => 0, 'msg' => 'ok', 'result' => $packages);
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "getProductPackages", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }


    /**
     * @Author:      lyt
     * @DateTime:    2016-01-25 12:11:39
     * @Description: 删除产品包
     */
    public function delProduct(){
        $validator = Validator::make(Input::all(),
            array(
                'token'    => 'required',
                'order_id' => 'required',
                "order_product_id"  => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok','result'=>array('order_id'=>Input::get('order_id')));
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $orders=Orders::find(Input::get('order_id'));
            if(is_null($orders)){
                $response = Lang::get("scs_error.order_notexiet_40000");
                break;
            }
            if($orders->shop_id!=$sc_user->shop_id){
                $response = Lang::get("scs_error.order_note_shop_error_40003");
                break;
            }
            if($orders->order_type==1){
                if(!in_array($orders->status,Orders::$delete_product)){//订单状态是正确
                    $response = Lang::get("scs_error.order_status_error_40022");
                    break;
                }
            }else{
                if($orders->status!=1411){//订单状态是正确
                    $response = Lang::get("scs_error.order_status_error_40022");
                    break;
                }
            }
            $op=OrderPay::where("order_id",$orders->order_id)->whereIn("status",array(0,1,5,7))->first();      
            if($op){//订单状态是否为服务结束状态
                $response = Lang::get("scs_error.order_pay_record_40112");
                break;
            } 
            $order_product=OrderProduct::find(Input::get("order_product_id"));
            if(is_null($order_product)||$order_product->order_id!=$orders->order_id){
                $response = Lang::get("scs_error.order_product_notexit_40006");
                break;
            }
            if($order_product->status!=1){
                $response = Lang::get("scs_error.order_product_status_error_40009");
                break;
            }
            $response=OrderProduct::deleteProduct($order_product,$sc_user->id);
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "delProduct", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /**
     * @Author:      zwh
     * @DateTime:    2016-3-3 09:41:27
     * @Description: 删除非标产品包中配件
     */
    public function delProductItem(){
        $validator = Validator::make(Input::all(),
            array(
                'token'    => 'required',
                'order_id' => 'required',
                "order_product_id"  => 'required',
                'item_id' => 'required'
            )
            );
        $response = array('code' => 0, 'msg' => 'ok','result'=>array('order_id'=>Input::get('order_id')));
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $orders=Orders::find(Input::get('order_id'));
            if(is_null($orders)){
                $response = Lang::get("scs_error.order_notexiet_40000");
                break;
            }
            if($orders->shop_id!=$sc_user->shop_id){
                $response = Lang::get("scs_error.order_note_shop_error_40003");
                break;
            }
            if($orders->order_type==1){
                if(!in_array($orders->status,Orders::$delete_product)){//订单状态是正确
                    $response = Lang::get("scs_error.order_status_error_40022");
                    break;
                }
            }else{
                if($orders->status!=1411){//订单状态是正确
                    $response = Lang::get("scs_error.order_status_error_40022");
                    break;
                }
            }
            $op=OrderPay::where("order_id",$orders->order_id)->whereIn("status",array(0,1,5,7))->first();      
            if($op){//订单状态是否为服务结束状态
                $response = Lang::get("scs_error.order_pay_record_40112");
                break;
            } 
            $order_product=OrderProduct::find(Input::get("order_product_id"));
            if(is_null($order_product)||$order_product->order_id!=$orders->order_id){
                $response = Lang::get("scs_error.order_product_notexit_40006");
                break;
            }
            if($order_product->status!=1){
                $response = Lang::get("scs_error.order_product_status_error_40009");
                break;
            }
            $opns=OrderProductNonStandard::where('id',Input::get('item_id'))->where('status',1)->first();
            if(!$opns){
                $response = Lang::get("scs_error.order_product_notexit_40006");
                break;
            }

            $moo=MaintenanceOutOrder::where("product_type","non_standard")->where("product_item_id",$opns->id)->whereIn("status",array(0,1,2))->first();
            if($moo){//如果存在 备货中或者 等待领料的 出库申请  不允许删除
                $response = Lang::get("scs_error.order_product_item_out_error_40008");
                break;
            }

            if($opns->service_type==1&&$opns->type==0){
                OrderSmyFilling::where("order_id",$orders->order_id)->where("product_item_id",$opns->id)->where("product_type",'non_standard')->update(array("status"=>0));
            }

            $opns->status=0;
            $opns->save();

            //订单应付金额及优惠信息将重新计算，废弃原有再优惠信息上加减
            Orders::calculate(Input::get('order_id'));

            $moo=MaintenanceOutOrder::where("product_type","non_standard")->where("product_item_id",$opns->id)->whereIn("status",array(3,4))->first();
            // if($moo){
            //     $moo->delete();
            // }
            $opr=new OrderProductRecord();
            $opr->order_id=$orders->order_id;
            $opr->product_type='non_standard';
            $opr->operation_type='delete';
            $opr->num=1;
            $opr->operation_grade='二级';
            $opr->user_id=$sc_user->id;
            $opr->user_type='sc';
            $opr->operation_id=$opns->id;
            $opr->name=$opns->name;
            $opr->amount=$opns->amount;
            $opr->save();
            $response=array('code' => 0, 'msg' => 'ok', 'result' => array("order_id"=>$order_product->order_id));
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "delProductItem", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }


    /**
     * @Author:      lyt
     * @DateTime:    2016-01-26 09:27:10
     * @Description: 用于更改基础产品的条目数量
     */
    public function changeBaseProductItemNum(){
        $validator = Validator::make(Input::all(),
            array(
                'token'    => 'required',
                'order_id' => 'required',
                'item_id'=> 'required',
                'number'=> 'required|numeric|min:0|not_in:0',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok','result'=>array('order_id'=>Input::get('order_id')));
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $orders=Orders::find(Input::get('order_id'));
            if(is_null($orders)){
                $response = Lang::get("scs_error.order_notexiet_40000");
                break;
            }
            if($orders->shop_id!=$sc_user->shop_id){
                $response = Lang::get("scs_error.order_note_shop_error_40003");
                break;
            }
            if($orders->order_type==1){
                if(!in_array($orders->status,Orders::$add_product)){//订单状态是正确
                    $response = Lang::get("scs_error.order_status_error_40022");
                    break;
                }
            }else{
                if($orders->status!=1411){//订单状态是正确
                    $response = Lang::get("scs_error.order_status_error_40022");
                    break;
                }
            }
            $op=OrderPay::where("order_id",$orders->order_id)->whereIn("status",array(0,1,5,7))->first();      
            if($op){//订单状态是否为服务结束状态
                $response = Lang::get("scs_error.order_pay_record_40112");
                break;
            }  
            $opbi=OrderProductBaseItem::find(Input::get("item_id"));
            if(is_null($opbi)||$opbi->order_id!=$orders->order_id||$opbi->type!=1){
                $response = Lang::get("scs_error.order_product_item_notexit_40011");
                break;
            }
            $order_product=OrderProduct::find($opbi->order_product_package_id);
            if(is_null($order_product)||$order_product->order_id!=$orders->order_id){
                $response = Lang::get("scs_error.order_product_notexit_40006");
                break;
            }
            if($order_product->status!=1){
                $response = Lang::get("scs_error.order_product_status_error_40009");
                break;
            }
            $number=Input::get("number");
            $amount=Input::get("amount")*100;
            if($number==$opbi->num&&$amount==$opbi->amount){
                $response = array('code' => 0, 'msg' => 'ok', 'result' => array("order_id"=>$order_product->order_id,"order_product_amount"=>$order_product->amount,"order_amount"=>$orders->amount));
                break;
            }
            $response=OrderProductBaseItem::changeProductItemNum(Input::get('order_id'),$opbi,$number,$amount,$sc_user->id);
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "changeBaseProductItemNum", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }


    /**
     * @Author:      lyt
     * @DateTime:    2016-01-28 09:24:52
     * @Description: 用于更换基础产品包的耗材型号
     */
    public function changeBaseProductItem(){
        $validator = Validator::make(Input::all(),
            array(
                'token'    => 'required',
                'order_id' => 'required',
                'order_product_base_item_id'=> 'required',//订单耗材的id
                'new_item_id'=> 'required',
                // 'type' => 'required'//0为标准耗材1为非标
            )
        );
        $response = array('code' => 0, 'msg' => 'ok','result'=>array('order_id'=>Input::get('order_id')));
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $orders=Orders::find(Input::get('order_id'));
            if(is_null($orders)){
                $response = Lang::get("scs_error.order_notexiet_40000");
                break;
            }
            if($orders->shop_id!=$sc_user->shop_id){
                $response = Lang::get("scs_error.order_note_shop_error_40003");
                break;
            }
            if($orders->order_type==1){
                if(!in_array($orders->status,Orders::$add_product)){//订单状态是正确
                    $response = Lang::get("scs_error.order_status_error_40022");
                    break;
                }
            }else{
                if($orders->status!=1411){//订单状态是正确
                    $response = Lang::get("scs_error.order_status_error_40022");
                    break;
                }
            }
            $op=OrderPay::where("order_id",$orders->order_id)->whereIn("status",array(0,1,5,7))->first();      
            if($op){//订单状态是否为服务结束状态
                $response = Lang::get("scs_error.order_pay_record_40112");
                break;
            }  
            $opbi=OrderProductBaseItem::find(Input::get("order_product_base_item_id"));
            if(is_null($opbi)||$opbi->order_id!=$orders->order_id||$opbi->type!=1){
                $response = Lang::get("scs_error.order_product_item_notexit_40011");
                break;
            }
            $order_product=OrderProduct::find($opbi->order_product_package_id);
            if(is_null($order_product)||$order_product->order_id!=$orders->order_id){
                $response = Lang::get("scs_error.order_product_notexit_40006");
                break;
            }
            if($order_product->status!=1){
                $response = Lang::get("scs_error.order_product_status_error_40009");
                break;
            }
            $csi=DataCarStandardInfo::find($orders->car_model_id);
            if(is_null($csi)){
                $response = Lang::get("scs_error.order_car_model_notexit_40002");
                break;
            }
            $wmcf=WorkModelCoefficient::where("name",$csi->model_level)->first();
            if(is_null($wmcf)){
                $response = Lang::get("scs_error.work_mcf_error_10002");
                break;
            }

            //要更换成的配件类型判断
            $si=SupplyItem::find(Input::get("new_item_id"));
            // if(Input::get('type')==0){
                $mw=MaintenanceWarehouse::where('item_id',Input::get('new_item_id'))->where('shop_id',$sc_user->shop_id)->first();
                if(!$mw || $opbi->num>$mw->number){
                    $response = Lang::get("scs_error.supply_item_low_stocks_40005");
                    break;
                }
                
                //更换耗材的加价系数
                if(Orders::isSale($si->id,0)){
                    $response = Lang::get("scs_error.supply_error_10011");
                    break;
                }
                if($si->type==1||PriceBargaining::ischange($si->id,$orders->shop_id)==1){//如果能编辑价格
                    $si->amount=Input::get("amount")*100;
                    $max=MaintenanceStorageItem::where('item_id',Input::get('new_item_id'))->where('shop_id',$sc_user->shop_id)->where('type',1)->where('current_number','>',0)->where('status',1)->max('tax_purchase_price');
                    if($si->amount < $max){
                        $response = Lang::get("scs_error.data_price_error_61018");
                        break;
                    }
                }else{
                    $wpc=WorkPartsCoefficient::where("car_model_name",$csi->model_level)->where("supply_brand_id",$si->brand_id)->where("supply_subject_id",$si->supply_classification_id)->where("status",1)->first();
                    $wmcf->supply_coefficient = null;
                    if (!empty($wpc)) {
                        $wpc_city=WorkPartsCoefficientCity::where('city_id',$sc_user->shop->city_id)->where('coefficient_id',$wpc->id)->where('status',1)->first();
                        $wmcf->supply_coefficient=isset($wpc_city->coefficient) ? $wpc_city->coefficient : null; //如果有城市系数，优先使用。
                    }
                    if ($wmcf->supply_coefficient == null){ //如果是0，说明没有赋值
                        $wmcf->supply_coefficient=isset($wpc->coefficient) ? $wpc->coefficient : 1;
                    }
                    //更换多城市价格
                    // $sip=SupplyItemPrice::where("item_id",$si->id)->where("city_id",$sc_user->shop->city_id)->first();
                    // if($sip){
                    //     $si->amount=$sip->price;
                    // }
                    $sip=SupplyCityPrice::where("supply_id",$si->id)->where("city_id",$sc_user->shop->city_id)->where("status",1)->first();
                    if($sip){
                        $si->amount=$sip->price;
                    }else{
                        $ss_temp=SupplySub::where("supply_id",$si->id)->where("status",1)->first();
                        $si->amount=isset($ss_temp)?$ss_temp->usual_price:0;
                    }                    
                    $si->amount=Common::upFow($si->amount*$wmcf->supply_coefficient);
                }                         
            // }else{
            //     $mw=MaintenanceWarehouse::where('item_id',Input::get('new_item_id'))->where('shop_id',$sc_user->shop_id)->where('item_type',1)->first();
            //     if(!$mw || $opbi->num>$mw->number){
            //         $response = Lang::get("scs_error.supply_item_low_stocks_40005");
            //         break;
            //     }
            //     $max=MaintenanceStorageItem::where('item_id',Input::get('new_item_id'))->where('type',1)->where('item_type',1)->where('current_number','>',0)->where('status',1)->max('tax_purchase_price');
            //     if(Input::get('amount')*100 < $max){
            //         $response = Lang::get("scs_error.data_price_error_61018");
            //         break;
            //     }
            //     $si=SupplyItemNonStandard::find(Input::get("new_item_id"));
            //     if(Orders::isSale($si->id,1)){
            //         $response = Lang::get("scs_error.supply_error_10011");
            //         break;
            //     }
            //     $si->amount=Input::get("amount")*100;//如果是非标的 更新非标为传过来的价格
            // }

            //原有配件类型判断
            // if($opbi->item_type==0){
                $old_si=SupplyItem::find($opbi->item_id);
            // }else{
            //     $old_si=SupplyItemNonStandard::find($opbi->item_id);
            // }
            // if(is_null($si)||$si->status!=1){
            //     $response = Lang::get("scs_error.supply_item_not_exit_41000");
            //     break;
            // }
            //如果更换非标不进行 耗材品类判断
            if($si->type==0){
                $temp_subject=($opbi->temp_subject==0)?$old_si->supply_classification_id:$opbi->temp_subject;//如果
                if($temp_subject!=$si->supply_classification_id){
                    $response = Lang::get("scs_error.supply_subject_error_41002");
                    break;
                }
            }
            //第一次更换耗材记录该耗材的；品类 为了以后更换标准耗材判断 
            if($opbi->temp_subject==0){
                $opbi->temp_subject=$old_si->supply_classification_id;
            }
            

            // $number=Input::get("number");
            // if($number==$opbi->num){
            //     $response = array('code' => 0, 'msg' => 'ok', 'result' => array("order_id"=>$order_product->order_id,"order_product_amount"=>$order_product->amount,"order_amount"=>$orders->amount));
            //     break;
            // }
            
            $response=OrderProductBaseItem::changeProductItem(Input::get('order_id'),$opbi,$si,$sc_user->id,$si->type);
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "changeBaseProductItem", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     * @Author:      zwh
     * @DateTime:    2016-11-7 10:41:48
     * @Description: 用于无适配耗材更换基础产品包的耗材
     */
    public function changeNoAdapterBaseProductItem(){
        $validator = Validator::make(Input::all(),
            array(
                'token'    => 'required',
                'order_id' => 'required',
                'order_product_base_item_id'=> 'required',//order_product_base_item的id
                'new_item_id'=> 'required',
                // 'type' => 'required'//0为标准耗材1为非标
            )
        );
        $response = array('code' => 0, 'msg' => 'ok','result'=>array('order_id'=>Input::get('order_id')));
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $orders=Orders::find(Input::get('order_id'));
            if(is_null($orders)){
                $response = Lang::get("scs_error.order_notexiet_40000");
                break;
            }
            if($orders->shop_id!=$sc_user->shop_id){
                $response = Lang::get("scs_error.order_note_shop_error_40003");
                break;
            }
            if($orders->order_type==1){
                if(!in_array($orders->status,Orders::$add_product)){//订单状态是正确
                    $response = Lang::get("scs_error.order_status_error_40022");
                    break;
                }
            }else{
                if($orders->status!=1411){//订单状态是正确
                    $response = Lang::get("scs_error.order_status_error_40022");
                    break;
                }
            }
            $op=OrderPay::where("order_id",$orders->order_id)->whereIn("status",array(0,1,5,7))->first();      
            if($op){//订单状态是否为服务结束状态
                $response = Lang::get("scs_error.order_pay_record_40112");
                break;
            }  
            $opbi=OrderProductBaseItem::find(Input::get("order_product_base_item_id"));
            if(is_null($opbi)||$opbi->order_id!=$orders->order_id){
                $response = Lang::get("scs_error.order_product_item_notexit_40011");
                break;
            }
            $order_product=OrderProduct::find($opbi->order_product_package_id);
            if(is_null($order_product)||$order_product->order_id!=$orders->order_id){
                $response = Lang::get("scs_error.order_product_notexit_40006");
                break;
            }
            if($order_product->status!=1){
                $response = Lang::get("scs_error.order_product_status_error_40009");
                break;
            }
            $csi=DataCarStandardInfo::find($orders->car_model_id);
            if(is_null($csi)){
                $response = Lang::get("scs_error.order_car_model_notexit_40002");
                break;
            }
            $wmcf=WorkModelCoefficient::where("name",$csi->model_level)->first();
            if(is_null($wmcf)){
                $response = Lang::get("scs_error.work_mcf_error_10002");
                break;
            }
            $si=SupplyItem::find(Input::get("new_item_id"));
            //要更换成的配件类型判断            
            // if(Input::get('type')==0){
                $mw=MaintenanceWarehouse::where('item_id',Input::get('new_item_id'))->where('shop_id',$sc_user->shop_id)->first();
                if(!$mw || $opbi->num>$mw->number){
                    $response = Lang::get("scs_error.supply_item_low_stocks_40005");
                    break;
                }
                // $si=SupplyItem::find(Input::get("new_item_id"));
        
                //更换耗材的加价系数
                if(Orders::isSale($si->id,0)){
                    $response = Lang::get("scs_error.supply_error_10011");
                    break;
                }

                if($si->type==1||PriceBargaining::ischange($si->id,$orders->shop_id)==1){//如果能编辑价格
                    $si->amount=Input::get("amount")*100;
                    $max=MaintenanceStorageItem::where('item_id',Input::get('new_item_id'))->where('type',1)->where('current_number','>',0)->where('status',1)->max('tax_purchase_price');
                    if($si->amount < $max){
                        $response = Lang::get("scs_error.data_price_error_61018");
                        break;
                    }
                }else{
                    $wpc=WorkPartsCoefficient::where("car_model_name",$csi->model_level)->where("supply_brand_id",$si->brand_id)->where("supply_subject_id",$si->supply_classification_id)->where("status",1)->first();
                    $wmcf->supply_coefficient = null;
                    if (!empty($wpc)) {
                        $wpc_city=WorkPartsCoefficientCity::where('city_id',$sc_user->shop->city_id)->where('coefficient_id',$wpc->id)->where('status',1)->first();
                        $wmcf->supply_coefficient=isset($wpc_city->coefficient) ? $wpc_city->coefficient : null; //如果有城市系数，优先使用。
                    }
                    if ($wmcf->supply_coefficient == null){ //如果是0，说明没有赋值
                        $wmcf->supply_coefficient=isset($wpc->coefficient) ? $wpc->coefficient : 1;
                    }
                    //更换多城市价格
                    // $sip=SupplyItemPrice::where("item_id",$si->id)->where("city_id",$sc_user->shop->city_id)->first();
                    // if($sip){
                    //     $si->amount=$sip->price;
                    // }
                    $sip=SupplyCityPrice::where("supply_id",$si->id)->where("city_id",$sc_user->shop->city_id)->where("status",1)->first();
                    if($sip){
                        $si->amount=$sip->price;
                    }else{
                        $ss_temp=SupplySub::where("supply_id",$si->id)->where("status",1)->first();
                        $si->amount=isset($ss_temp)?$ss_temp->usual_price:0;
                    }                    

                    $si->amount=Common::upFow($si->amount*$wmcf->supply_coefficient);
                }                
                 
            // }else{
            //     $mw=MaintenanceWarehouse::where('item_id',Input::get('new_item_id'))->where('shop_id',$sc_user->shop_id)->where('item_type',1)->first();
            //     if(!$mw || $opbi->num>$mw->number){
            //         $response = Lang::get("scs_error.supply_item_low_stocks_40005");
            //         break;
            //     }
            //     $max=MaintenanceStorageItem::where('item_id',Input::get('new_item_id'))->where('type',1)->where('item_type',1)->where('current_number','>',0)->where('status',1)->max('tax_purchase_price');
            //     if(Input::get('amount')*100 < $max){
            //         $response = Lang::get("scs_error.data_price_error_61018");
            //         break;
            //     }
            //     $si=SupplyItemNonStandard::find(Input::get("new_item_id"));
            //     if(Orders::isSale($si->id,1)){
            //         $response = Lang::get("scs_error.supply_error_10011");
            //         break;
            //     }
            //     $si->amount=Input::get("amount")*100;//如果是非标的 更新非标为传过来的价格
            // }
    
            // if(is_null($si)||$si->status!=1){
            //     $response = Lang::get("scs_error.supply_item_not_exit_41000");
            //     break;
            // }
            //如果更换非标不进行 耗材品类判断
            if($si->type==0){
                if($opbi->item_id!=$si->supply_classification_id){
                    $response = Lang::get("scs_error.supply_subject_error_41002");
                    break;
                }
            }
            //第一次更换耗材记录该耗材的；品类 为了以后更换标准耗材判断 
            // if($opbi->temp_subject==0){
            $opbi->temp_subject=$opbi->item_id;
            // }
    
            // $number=Input::get("number");
            // if($number==$opbi->num){
            //     $response = array('code' => 0, 'msg' => 'ok', 'result' => array("order_id"=>$order_product->order_id,"order_product_amount"=>$order_product->amount,"order_amount"=>$orders->amount));
            //     break;
            // }
            $response=OrderProductBaseItem::changeProductItem(Input::get('order_id'),$opbi,$si,$sc_user->id,$si->type);
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "changeBaseProductItem", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }


    /**
     * @Author:      lyt
     * @DateTime:    2016-01-28 14:27:09
     * @Description: 用于修改 非标产品的 条目数量
    */
    // public function changeNonProductItemNum(){
    //     $validator = Validator::make(Input::all(),
    //         array(
    //             'token'    => 'required',
    //             'order_id' => 'required',
    //             'item_id'=> 'required',
    //             'number'=> 'required|numeric|min:0|not_in:0',
    //         )
    //     );
    //     $response = array('code' => 0, 'msg' => 'ok','result'=>array('order_id'=>Input::get('order_id')));
    //     do{
    //         if($validator->fails()) {
    //             $response = Lang::get("scs_error.args_error_10000");
    //             $response["result"]=$validator->messages()->all();
    //             break;
    //         }
    //         $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
    //         if(is_null($sc_user)){
    //             break;
    //         }
    //         $orders=Orders::find(Input::get('order_id'));
    //         if(is_null($orders)){
    //             $response = Lang::get("scs_error.order_notexiet_40000");
    //             break;
    //         }
    //         if($orders->shop_id!=$sc_user->shop_id){
    //             $response = Lang::get("scs_error.order_note_shop_error_40003");
    //             break;
    //         }
    //         if($orders->order_type==1){
    //             if(!in_array($orders->status,Orders::$add_product)){//订单状态是正确
    //                 $response = Lang::get("scs_error.order_status_error_40022");
    //                 break;
    //             }
    //         }else{
    //             if($orders->status!=1411){//订单状态是正确
    //                 $response = Lang::get("scs_error.order_status_error_40022");
    //                 break;
    //             }
    //         }
    //         $op=OrderPay::where("order_id",$orders->order_id)->whereIn("status",array(0,1,5,7))->first();      
    //         if($op){//订单状态是否为服务结束状态
    //             $response = Lang::get("scs_error.order_pay_record_40112");
    //             break;
    //         }  
    //         $opns=OrderProductNonStandard::where('id',Input::get("item_id"))->where('status',1)->first();
    //         if(is_null($opns)||$opns->order_id!=$orders->order_id){
    //             $response = Lang::get("scs_error.order_product_item_notexit_40011");
    //             break;
    //         }
    //         $order_product=OrderProduct::find($opns->order_product_id);
    //         if(is_null($order_product)||$order_product->order_id!=$orders->order_id){
    //             $response = Lang::get("scs_error.order_product_notexit_40006");
    //             break;
    //         }
    //         if($order_product->status!=1){
    //             $response = Lang::get("scs_error.order_product_status_error_40009");
    //             break;
    //         }
    //         $number=Input::get("number");
    //         if($number==$opns->num){
    //             $response = array('code' => 0, 'msg' => 'ok', 'result' => array("order_id"=>$order_product->order_id,"order_product_amount"=>$order_product->amount,"order_amount"=>$orders->amount));
    //             break;
    //         }
    //         $response=OrderProductNonStandard::changeProductItemNum($order_product,$opns,$number,$sc_user->id);
    //     }while(false);
    //     Log::info("info", array("system" => "scs" ,"event" => "changeNonProductItemNum", 'input' =>Input::all() ,"output" => $response));
    //     return json_encode($response);
    // }


    /**
     * @Author:      lyt
     * @DateTime:    2016-01-29 14:14:28
     * @Description: 用于添加基础的产品 项目
     */
    //废弃的方法 注释掉实验  18-01-09 lyt
    // public function addBaseItem(){
    //     $validator = Validator::make(Input::all(),
    //         array(
    //             'token'    => 'required',
    //             'order_id' => 'required',
    //             'item_id'=> 'required',
    //             'number'=> 'required|numeric|min:1',
    //         )
    //     );
    //     $response = array('code' => 0, 'msg' => 'ok','result'=>array('order_id'=>Input::get('order_id')));
    //     do{
    //         if($validator->fails()) {
    //             $response = Lang::get("scs_error.args_error_10000");
    //             $response["result"]=$validator->messages()->all();
    //             break;
    //         }
    //         $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
    //         if(is_null($sc_user)){
    //             break;
    //         }
    //         $orders=Orders::find(Input::get('order_id'));
    //         if(is_null($orders)){
    //             $response = Lang::get("scs_error.order_notexiet_40000");
    //             break;
    //         }
    //         if($orders->shop_id!=$sc_user->shop_id){
    //             $response = Lang::get("scs_error.order_note_shop_error_40003");
    //             break;
    //         }
    //         if($orders->order_type==1){
    //             if(!in_array($orders->status,Orders::$add_product)){//订单状态是正确
    //                 $response = Lang::get("scs_error.order_status_error_40022");
    //                 break;
    //             }
    //         }else{
    //             if($orders->status!=1411){//订单状态是正确
    //                 $response = Lang::get("scs_error.order_status_error_40022");
    //                 break;
    //             }
    //         }
    //         $op=OrderPay::where("order_id",$orders->order_id)->whereIn("status",array(0,1,5,7))->first();      
    //         if($op){//订单状态是否为服务结束状态
    //             $response = Lang::get("scs_error.order_pay_record_40112");
    //             break;
    //         }  
    //         $csi=DataCarStandardInfo::find($orders->car_model_id);
    //         if(is_null($csi)){//只进行 车型存在 不对车型状态进行祥判断
    //             $response = Lang::get("scs_error.order_car_model_notexit_40002");
    //             break;
    //         }
    //         $wmcf=WorkModelCoefficient::where("name",$csi->model_level)->first();
    //         if(is_null($wmcf)){
    //             $response = Lang::get("scs_error.work_mcf_error_10002");
    //             break;
    //         }
    //         $si=SupplyItem::find(Input::get("item_id"));
    //         if(is_null($si)||$si->status!=1){//如果 耗材不存在或者 状态不正确
    //             $response = Lang::get("scs_error.supply_item_not_exit_41000");
    //             break;
    //         }
    //         //更换耗材的加价系数
    //         $wpc=WorkPartsCoefficient::where("car_model_name",$csi->model_level)->where("supply_brand_id",$si->brand_id)->where("supply_subject_id",$si->subject)->where("status",1)->first();
    //         $wmcf->supply_coefficient = null;
    //         if (!empty($wpc)) {
    //             $wpc_city=WorkPartsCoefficientCity::where('city_id',$sc_user->shop->city_id)->where('coefficient_id',$wpc->id)->where('status',1)->first();
    //             $wmcf->supply_coefficient=isset($wpc_city->coefficient) ? $wpc_city->coefficient : null; //如果有城市系数，优先使用。
    //         }
    //         if ($wmcf->supply_coefficient == null){ //如果是0，说明没有赋值
    //             $wmcf->supply_coefficient=isset($wpc->coefficient) ? $wpc->coefficient : 1;
    //         }
    //         //更换多城市价格
    //         $sip=SupplyItemPrice::where("item_id",$si->id)->where("city_id",$sc_user->shop->city_id)->first();
    //         if($sip){
    //             $si->amount=$sip->price;
    //         }

    //         $spi=SupplyProductItem::where("car_model_id",$csi->id)->where("supply_item_id",$si->id)->where("status",1)->first();
    //         if(is_null($spi)){
    //             $response = Lang::get("scs_error.supply_item_car_model_error_41001");
    //             break;
    //         }
    //         //耗材存在  订单状态正常 添加 该项目
    //         $response=OrderProductNonStandard::saveBaseItem($si,$orders->order_id,$sc_user->id,$wmcf,Input::get("number"));
    //     }while(false);
    //     Log::info("info", array("system" => "scs" ,"event" => "addBaseItem", 'input' =>Input::all() ,"output" => $response));
    //     return json_encode($response);
    // }
    /**
     * @Author:      zwh
     * @DateTime:    2016-1-20 16:36:34
     * @Description: 用于添加 订单的产品项（多个）到新订单
     */
    public function addProductsToNewOrder(){
        $validator = Validator::make(Input::all(),
            array(
                'token'    => 'required',
                "pack_id"  => 'required',
                'car_no'=>'required|max:20',
                'car_model_id'=>'required|max:20|alpha_dash',
                "mileage"=>'required',
                "vin"=>'required',
                "note"=>'max:100',
                "insurance"=>'date',
                "user_id"=>'required'
            )
            );
        $success = array();
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            if(Orders::createOrderBefore(Input::get('car_no'),$sc_user->shop_id,1)){
                $response = Lang::get("scs_error.order_create_error_40066");
                break;
            }
            $csi=DataCarStandardInfo::find(Input::get("car_model_id"));
            if(is_null($csi)){
                $response = Lang::get("scs_error.order_car_model_notexit_40002");
                break;
            }
            $user=Users::find(Input::get('user_id'));
            if($user->status!=1){
                $response = Lang::get("scs_error.order_cusuom_error_40004");
                $response["result"]=$validator->messages()->all();
                break;
            }
            
            /*保养手册添加订单用户肯定存在
            if($user){//如果存在用户判断用户
                
            }else{
                $user=new Users;
                $user->phone=Input::get("phone");
                $user->real_name=Input::get("name");
                $user->area=Input::get("area","010");
                $user->status=1;
                $user->register_source_id=14;//门店
                $user->save();
            }
            */
            $uci=UserCarInfo::where("user_id",$user->id)->where("car_no",Input::get("car_no"))->where("status",1)->first();
            if($uci){//如果用户存在该车辆
                // if(Input::get('mileage')<$uci->mileage){//如果 这次保养的里程 小于
                //     $response = Lang::get("scs_error.order_mileage_error_40030");
                //     break;
                // }
                if($uci->is_lock==1){//如果是认证车辆
                    //修改其他车型不同的的认证车辆 认证状态为未认证
                    UserCarInfo::where("car_no",Input::get("car_no"))->where("is_lock",1)->where("car_model_id","!=",$csi->id)->update(array("is_lock"=>0));
                    UserCarInfo::where("id",$uci->id)->update(array("is_lock"=>1));
                    //修改认证车型信息
                    $uacs=UserAuthenticationCar::where('car_no',$uci->car_no)->where('car_model_id',$csi->id)->where('status',1)->get();
                    if(!sizeof($uacs)){
                        UserAuthenticationCar::where("car_no",$uci->car_no)->update(array("status"=>0));
                        $uac=new UserAuthenticationCar();
                        $uac->status=1;
                        $uac->car_no=$uci->car_no;
                        $uac->vin_code=strtoupper(Input::get("vin"));
                        $uac->mileage=$uci->mileage;
                        $uac->car_brand_id=$csi->brand_name_id;
                        $uac->car_series_id=$csi->series_name_id;
                        $uac->car_model_id=$csi->id;
                        $uac->user_id=$uci->user_id;
                        $uac->shop_id=$sc_user->shop_id;
                        $uac->create_by=$sc_user->id;
                        $uac->shop_id=$sc_user->shop_id;
                        $uac->save();
                    }
                }

            }else{//如果不存在该车辆
                $uci=new UserCarInfo;
                $uci->car_no = strtoupper(Input::get('car_no'));
                $uci->user_id = $user->id;
                $uci->status = 1;
                $uci->is_default = 0;
                $uci->car_level = 0;
                $uci->is_lock = 0;
                $uci->mileage =0;
            }
            $uci->car_series_id = $csi->series_name_id;
            $uci->car_brand_id = $csi->brand_name_id;
            $uci->car_model_id = $csi->id;
            $uci->vin_code = strtoupper(Input::get("vin"));
            // $uci->mileage =Input::get('mileage')?Input::get('mileage'):0;
            $uci->note=Input::get("note");
            $uci->insurance=Input::get("insurance");
            $uci->start_off_time=Input::get("start_off_time");
            $uci->save();

            $orders = new Orders();
            $order_id = Common::createOrderId();
            $orders->order_id = $order_id;
            $orders->user_id =$user->id;
            $orders->city = Input::get('city_id')?Input::get('city_id'):1;
            $orders->place = 2;
            $orders->book_time =date("Y-m-d",time()) ;
            $orders->book_hour ="";
            $orders->shop_id = $sc_user->shop_id;
            $orders->address = "";
            $orders->name = $user->real_name;
            $orders->tittle = isset($user->sex) && $user->sex==2 ? '女士' : '先生';
            $orders->phone = $user->phone;
            $orders->pay_type = 0;
            $orders->user_car_id = $uci->id;
            $orders->amount = 0;
            $orders->work_service =0;
            $orders->status =1412;
            $orders->note = Input::get("note","");
            $orders->car_brand_id = $csi->brand_name_id;
            $orders->car_brand_name = $csi->brand_name;
            $orders->car_series_id = $csi->series_name_id;
            $orders->car_series_name = $csi->series_name;
            $orders->car_model_id = $csi->id;
            $orders->car_model_name = $csi->model_name;
            $orders->car_no = $uci->car_no;
            $orders->outer_order_id = 0;
            $orders->engineer_id = 0;
            $orders->car_id = 0;
            $orders->mileage = $uci->mileage;
            $orders->oil_meter = 0;
            $orders->order_source = 14;//门店
            $orders->product_comment = "";
            $orders->book_type = 2;
            $orders->order_type= 1;
            $orders->save();

            $order_flows = new OrderFlows;
            $order_flows->order_id = $order_id;
            $order_flows->status =1411;
            $order_flows->user_id = $sc_user->id;
            $order_flows->type = 'sc';
            $order_flows->save();

            $order_flows = new OrderFlows;
            $order_flows->order_id = $order_id;
            $order_flows->status =1412;
            $order_flows->user_id = $sc_user->id;
            $order_flows->type = 'sc';
            $order_flows->save();

            $response['result']=array('order_id'=>$order_id);
            $pack_id = json_decode(Input::get('pack_id'),1);

            $whp=WorkHoursPrice::where("city_id",$sc_user->shop->city_id)->first();
            if(is_null($whp)){
                $response = Lang::get("scs_error.work_hour_error_10001");
                break;
            }
            $wmcf=WorkModelCoefficient::where("name",$csi->model_level)->first();
            if(is_null($wmcf)){
                $response = Lang::get("scs_error.work_mcf_error_10002");
                break;
            }


            //循环添加产品包
            foreach($pack_id as $pi){
                $package=ProductPackage::find($pi);
                if(is_null($package)){
                    $response = Lang::get("scs_error.package_error_50001");
                    break;
                }
                if($package->status!=1){
                    $response = Lang::get("scs_error.package_status_error_50002");
                    break;
                }
                // $ppc=ProductPackageCity::where("city_id",$orders->city)->where("status",1)->where("pack_id",$package->id)->first();
                $ppc=ProductPackageShop::isShopPackage($orders->shop_id,$package->id);
                if(!$ppc){
                    $response = Lang::get("scs_error.package_unable_error_50003");
                    break;
                }
                // if($package->city!=$sc_user->shop->city_id){
                //     $response = Lang::get("scs_error.package_unable_error_50003");
                //     break;
                // }
                $p_item=ProductPackage::getItem($orders->car_model_id,$package->id);
                if(sizeof($p_item["not_pin"])>0){//说明是存在没有匹配上的的耗材
                    continue;
                }
                $count_amount=0;
                $supply_arr=$p_item['supply'];
                $order_product_item=array();
                foreach ($supply_arr as $_sa) {
                    //更换耗材的加价系数
                    $wpc=WorkPartsCoefficient::where("car_model_name",$csi->model_level)->where("supply_brand_id",$_sa["brand_id"])->where("supply_subject_id",$_sa["subject"])->where("status",1)->first();
                    $wmcf->supply_coefficient = null;
                    if (!empty($wpc)) {
                        $wpc_city=WorkPartsCoefficientCity::where('city_id',$sc_user->shop->city_id)->where('coefficient_id',$wpc->id)->where('status',1)->first();
                        $wmcf->supply_coefficient=isset($wpc_city->coefficient) ? $wpc_city->coefficient : null; //如果有城市系数，优先使用。
                    }
                    if ($wmcf->supply_coefficient == null){ //如果是0，说明没有赋值
                        $wmcf->supply_coefficient=isset($wpc->coefficient) ? $wpc->coefficient : 1;
                    }
                    //更换多城市价格
                    // $sip=SupplyItemPrice::where("item_id",$_sa["id"])->where("city_id",$sc_user->shop->city_id)->first();
                    // if($sip){
                    //     $_sa["amount"]=$sip->price;
                    // }      
                    $sip=SupplyCityPrice::where("supply_id",$_sa["id"])->where("city_id",$sc_user->shop->city_id)->where("status",1)->first();
                    if($sip){
                        $_sa["amount"]=$sip->price;
                    }else{
                        $ss_temp=SupplySub::where("supply_id",$_sa["id"])->where("status",1)->first();
                        $_sa["amount"]=isset($ss_temp)?$ss_temp->usual_price:0;
                    }

                    $temp_amount=$_sa["amount"]*$wmcf->supply_coefficient;
                    $temp_amount=Common::upFow($temp_amount);
                    $order_product_item[]=array(
                        "item_id"=>$_sa["id"],
                        "item_name"=>$_sa["name"],
                        "amount"=>$temp_amount,
                        "num"=>$_sa["number"],
                        "type"=>1,
                        "unit"=>1,
                    );
                    $count_amount+=$temp_amount*$_sa["number"];
                }
                foreach ($p_item['server'] as $_se) {
                    $res=PricingStrategy::getStringStrategy($csi->id,$_se['id'],$sc_user->shop->city_id);
                    if($res['code']==0){
                        $temp_amount=$res['price'];
                    }else{
                        //判断工时类型为工时类型还是固定价格
                        if($_se['type'] ==1 ){
                            $temp_amount=$whp->price*$wmcf->work_coefficient*$_se["work_hours"];
                        }elseif($_se['type']==2){
                            $temp_amount=$_se["price"];
                        }
                    }
                    $order_product_item[]=array(
                        "item_id"=>$_se["id"],
                        "item_name"=>$_se["name"],
                        "amount"=>$temp_amount,
                        "num"=>$_se["work_hours"],
                        "type"=>2,
                        "unit"=>"个",
                    );
                    $count_amount+=$temp_amount;
                }
                $package_arr=array(array(
                    "product_id"=>$package->id,
                    "product_name"=>$package->name,
                    "amount"=>$count_amount,
                    "item"=>$order_product_item
                ));
                OrderProduct::saveBaseProducts($package_arr,"",$sc_user->id,$order_id);
                $success[]=array('pack_id'=>$package->id,'pack_name'=>$package->name);
            }

        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "addProduct", 'input' =>Input::all() ,"output" => $response));
        $response['success']=$success;
        return json_encode($response);
    }

    /**
     * @Author:      zwh
     * @DateTime:    2016-2-24 10:40:25
     * @Description: 用于添加 订单的服务
     */
    public function addService(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'order_id' => 'required',
                "service_id"=>'required',
            )
            );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $orders=Orders::find(Input::get('order_id'));
            if(is_null($orders)){
                $response = Lang::get("scs_error.order_notexiet_40000");
                break;
            }
            if($orders->shop_id!=$sc_user->shop_id){
                $response = Lang::get("scs_error.order_note_shop_error_40003");
                break;
            }
            if($orders->order_type==1){
                if(!in_array($orders->status,Orders::$add_product)){//订单状态是正确
                    $response = Lang::get("scs_error.order_status_error_40022");
                    break;
                }
            }else{
                if($orders->status!=1411){//订单状态是正确
                    $response = Lang::get("scs_error.order_status_error_40022");
                    break;
                }
            }
            $op=OrderPay::where("order_id",$orders->order_id)->whereIn("status",array(0,1,5,7))->first();      
            if($op){//订单状态是否为服务结束状态
                $response = Lang::get("scs_error.order_pay_record_40112");
                break;
            }

            $op=OrderPerformance::where('order_id',Input::get("order_id"))->first();
            if($op){//如果存在检测记录
                if(date("Y-m",strtotime($op->created_at))!=date("Y-m",time())){
                    $response = Lang::get("scs_error.order_checek_time_error_40079");
                    break;
                }
            }
            
            if($orders->order_type==1){
                $csi=DataCarStandardInfo::find($orders->car_model_id);
                if(is_null($csi)){
                    $response = Lang::get("scs_error.car_model_is_empty23000");
                    break;
                }
            }
            $service=Service::find(Input::get("service_id"));
            if(is_null($service)){
                $response = Lang::get("scs_error.package_error_50001");
                break;
            }
            $op=new OrderProduct();
            $op->status=1;
            $op->amount=0;
            $op->order_id=Input::get('order_id');
            $op->product_type='non_standard';
            $op->product_id=Input::get('service_id');
            $op->product_name=$service->name;
            $op->save();
            $opr=new OrderProductRecord();
            $opr->order_id=$orders->order_id;
            $opr->product_type='non_standard';
            $opr->operation_type='create';
            $opr->num=1;
            $opr->operation_grade='一级';
            $opr->user_id=$sc_user->id;
            $opr->user_type='sc';
            $opr->operation_id=$op->id;
            $opr->name=$op->product_name;
            $opr->amount=$op->amount;
            $opr->save();
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("order_id"=>Input::get('order_id')));
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "addService", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /**
     * @Author:      zwh
     * @DateTime:    2016-2-24 14:01:52
     * @Description: 用于添加 配件
     */
    public function addPart(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'order_id' => 'required',
                // 'type' => 'required',
                "item_id"=>'required',//supply_item的id
                'number'=> 'required|numeric|min:0|not_in:0',
                'order_product_id'=> 'required',
                'amount'=> 'min:0'
            )
            );
        $number=Input::get('number');
        $response = array('code' => 0, 'msg' => 'ok','result'=>array('order_id'=>Input::get('order_id')));
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }

            $response=DB::transaction(function () use ($number,$sc_user) {
                $orders=Orders::where('order_id',Input::get('order_id'))->lockForUpdate()->first();
                if(is_null($orders)){
                    return Lang::get("scs_error.order_notexiet_40000");
                }
                if($orders->shop_id!=$sc_user->shop_id){
                    return Lang::get("scs_error.order_note_shop_error_40003");
                }
                if($orders->order_type==1){
                    if(!in_array($orders->status,Orders::$add_product)){//订单状态是正确
                        return Lang::get("scs_error.order_status_error_40022");
                    }
                }else{
                    if($orders->status!=1411){//订单状态是正确
                        return Lang::get("scs_error.order_status_error_40022");
                    }
                }
                $op=OrderPay::where("order_id",$orders->order_id)->whereIn("status",array(0,1,5,7))->first();      
                if($op){//订单状态是否为服务结束状态
                    $response = Lang::get("scs_error.order_pay_record_40112");
                    return $response;
                }
                $si=SupplyItem::find(Input::get("item_id"));
                // if(is_null($si)||$si->status!=1){//如果 耗材不存在或者 状态不正确
                //     return Lang::get("scs_error.supply_item_not_exit_41000");
                // }
                $mw=MaintenanceWarehouse::where('item_id',Input::get('item_id'))->where('shop_id',$sc_user->shop_id)->first();
                if(!$mw || $number>$mw->number){
                    return Lang::get("scs_error.supply_item_low_stocks_40005");
                }
                $op=OrderProduct::where("id",Input::get('order_product_id'))->lockForUpdate()->first();
                if($op->status === 0){
                    return Lang::get("scs_error.order_delete_40017");
                }


                // if(Input::get('type')==0){
                    if($orders->order_type==1){
                        $csi=DataCarStandardInfo::find($orders->car_model_id);
                        if(is_null($csi)){//只进行 车型存在 不对车型状态进行祥判断
                            return Lang::get("scs_error.order_car_model_notexit_40002");
                        }
                        $wmcf=WorkModelCoefficient::where("name",$csi->model_level)->first();
                        if(is_null($wmcf)){
                            return Lang::get("scs_error.work_mcf_error_10002");
                        }
                    }
                    // $si=SupplyItem::find(Input::get("item_id"));
                    // if(is_null($si)||$si->status!=1){//如果 耗材不存在或者 状态不正确
                    //     return Lang::get("scs_error.supply_item_not_exit_41000");
                    // }

                    if(Orders::isSale($si->id,0)){
                        return Lang::get("scs_error.supply_error_10011");
                    }
                    // $ss=SupplySeries::find($si->series_id);
                    if($si->type==1||PriceBargaining::ischange($si->id,$orders->shop_id)==1){//如果能编辑价格
                        $temp_amount=Input::get("amount")*100;
                        $max=MaintenanceStorageItem::where('shop_id',$orders->shop_id)->where('item_id',Input::get('item_id'))->where('type',1)->where('current_number','>',0)->where('status',1)->max('tax_purchase_price');
                        if($temp_amount< $max){
                            return Lang::get("scs_error.data_price_error_61018");
                        } 
                    }else{                        
                        //更换耗材的加价系数
                        $wpc=WorkPartsCoefficient::where("car_model_name",$csi->model_level)->where("supply_brand_id",$si->brand_id)->where("supply_subject_id",$si->supply_classification_id)->where("status",1)->first();
                        $wmcf->supply_coefficient = null;
                        if (!empty($wpc)) {
                            $wpc_city=WorkPartsCoefficientCity::where('city_id',$sc_user->shop->city_id)->where('coefficient_id',$wpc->id)->where('status',1)->first();
                            $wmcf->supply_coefficient=isset($wpc_city->coefficient) ? $wpc_city->coefficient : null; //如果有城市系数，优先使用。
                        }
                        if ($wmcf->supply_coefficient == null){ //如果是0，说明没有赋值
                            $wmcf->supply_coefficient=isset($wpc->coefficient) ? $wpc->coefficient : 1;
                        }
                        //更换多城市价格
                        // $sip=SupplyItemPrice::where("item_id",$si->id)->where("city_id",$sc_user->shop->city_id)->first();
                        // if($sip){
                        //     $si->amount=$sip->price;
                        // }
                        $sip=SupplyCityPrice::where("supply_id",$si->id)->where("city_id",$sc_user->shop->city_id)->where("status",1)->first();
                        if($sip){
                            $si->amount=$sip->price;
                        }else{
                            $ss_temp=SupplySub::where("supply_id",$si->id)->where("status",1)->first();
                            $si->amount=isset($ss_temp)?$ss_temp->usual_price:0;
                        }   
                        $temp_amount=$si->amount*$wmcf->supply_coefficient;                        
                    }
                               
                    $temp_amount=Common::upFow($temp_amount);      
                    $item_info=SupplyItem::getCacheItemInfo($si->id);  
                    $opns=new OrderProductNonStandard;
                    $opns->order_id=$orders->order_id;
                    $opns->name=$item_info->name;
                    $opns->num=$number;
                    $opns->item_id=$si->id;
                    $opns->amount=$temp_amount;
                    $opns->order_product_id=Input::get('order_product_id');
                    $opns->work_station=0;
                    $opns->work_status="prepare";
                    $opns->type=$si->type;
                    $opns->service_type=1;
                    $opns->unit=$item_info->unit?$item_info->unit:'';
                    $opns->save();
                    //判断特殊油品
                    if(in_array($si->id,Config::get("smy.item_id"))){//如果新耗材是特殊油品
                        OrderSmyFilling::saveosf($orders->shop_id,$si->id,"non_standard",$opns->id,$orders->order_id);
                    } 
                    //订单应付金额及优惠信息将重新计算，废弃原有再优惠信息上加减
                    Orders::calculate(Input::get('order_id'));
                // }else{
                //     $sins=SupplyItemNonStandard::find(Input::get("item_id"));
                //     if(is_null($sins)||$sins->status!=1){//如果 耗材不存在或者 状态不正确
                //         return Lang::get("scs_error.supply_item_not_exit_41000");
                //     }
                //     if(Orders::isSale($sins->id,1)){
                //         return Lang::get("scs_error.supply_error_10011");
                //     }
                //     $max=MaintenanceStorageItem::where('item_id',Input::get('item_id'))->where('type',1)->where('item_type',1)->where('current_number','>',0)->where('status',1)->max('tax_purchase_price');
                //     if(Input::get('amount')*100 < $max){
                //         return Lang::get("scs_error.data_price_error_61018");
                //     }
                //     $sins->amount=Input::get("amount")*100;
                //     $opns=new OrderProductNonStandard;
                //     $opns->order_id=$orders->order_id;
                //     $opns->name=$sins->series_name." ".$sins->model;
                //     $opns->num=$number;
                //     $opns->item_id=$sins->id;
                //     $opns->amount=$sins->amount;
                //     $opns->order_product_id=Input::get('order_product_id');
                //     $opns->work_station=0;
                //     $opns->work_status="prepare";
                //     $opns->type=Input::get('type');
                //     $opns->service_type=1;
                //     $opns->unit=$sins->unit;
                //     $opns->save();

                //     //订单应付金额及优惠信息将重新计算，废弃原有再优惠信息上加减
                //     Orders::calculate(Input::get('order_id'));
                // }
                $opr=new OrderProductRecord();
                $opr->order_id=$orders->order_id;
                $opr->product_type='non_standard';
                $opr->operation_type='create';
                $opr->num=$number;
                $opr->operation_grade='二级';
                $opr->user_id=$sc_user->id;
                $opr->user_type='sc';
                $opr->operation_id=$opns->id;
                $opr->name=$opns->name;
                $opr->amount=$opns->amount;
                $opr->save();
                return array('code' => 0, 'msg' => 'ok', 'result' => array("order_id"=>Input::get('order_id')));
            });
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "addPart", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /**
     * @Author:      zwh
     * @DateTime:    2016-2-24 14:01:52
     * @Description: 用于添加 工时
     */
    public function addWorkHours(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'order_id' => 'required',
                'order_product_id'=> 'required',
                'amount' => 'required|numeric|min:0'
            )
            );
        $response = array('code' => 0, 'msg' => 'ok','result'=>array('order_id'=>Input::get('order_id')));
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $orders=Orders::find(Input::get('order_id'));
            if(is_null($orders)){
                $response = Lang::get("scs_error.order_notexiet_40000");
                break;
            }
            if($orders->shop_id!=$sc_user->shop_id){
                $response = Lang::get("scs_error.order_note_shop_error_40003");
                break;
            }
            if($orders->order_type){
                if(!in_array($orders->status,Orders::$add_product)){//订单状态是正确
                    $response = Lang::get("scs_error.order_status_error_40022");
                    break;
                }
            }else{
                if($orders->status!=1411){//订单状态是正确
                    $response = Lang::get("scs_error.order_status_error_40022");
                    break;
                }
            }
            $op=OrderPay::where("order_id",$orders->order_id)->whereIn("status",array(0,1,5,7))->first();      
            if($op){//订单状态是否为服务结束状态
                $response = Lang::get("scs_error.order_pay_record_40112");
                break;
            }
            if($orders->order_type==1){
                $csi=DataCarStandardInfo::find($orders->car_model_id);
                if(is_null($csi)){//只进行 车型存在 不对车型状态进行祥判断
                    $response = Lang::get("scs_error.order_car_model_notexit_40002");
                    break;
                }
            }
            $op=OrderProduct::find(Input::get('order_product_id'));
            if(is_null($op)||$op->product_type!='non_standard'){
                $response = Lang::get("scs_error.order_product_notexit_40006");
                break;
            }
            $opns=OrderProductNonStandard::where("order_product_id",$op->id)->where("service_type",2)->where('status',1)->first();
            if($opns){
                $response = Lang::get("scs_error.order_product_work_exit_40032");
                break;
            }
            $opns=new OrderProductNonStandard;
            $opns->order_id=$orders->order_id;
            $opns->name='工时费';
            $opns->num=0;
            $opns->amount=Input::get('amount')*100;
            $opns->order_product_id=Input::get('order_product_id');
            $opns->work_station=0;
            $opns->work_status="prepare";
            $opns->type=1;
            $opns->unit='个';
            $opns->service_type=2;
            $opns->save();

            $opr=new OrderProductRecord();
            $opr->order_id=$orders->order_id;
            $opr->product_type='non_standard';
            $opr->operation_type='create';
            $opr->num=0;
            $opr->operation_grade='二级';
            $opr->user_id=$sc_user->id;
            $opr->user_type='sc';
            $opr->operation_id=$opns->id;
            $opr->name=$opns->name;
            $opr->amount=$opns->amount;
            $opr->save();
            
            //订单应付金额及优惠信息将重新计算，废弃原有再优惠信息上加减
            Orders::calculate(Input::get('order_id'));
            
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("order_id"=>Input::get('order_id')));
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "addService", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /**
     * @Author:      zwh
     * @DateTime:    2016-2-24 17:53:04
     * @Description: 用于更换非标服务包的耗材型号
     */
    public function changeNonStandardItem(){
        $validator = Validator::make(Input::all(),
            array(
                'token'    => 'required',
                // 'type'   => 'required',
                'order_id' => 'required',
                'order_product_non_standard_id'=> 'required',//OrderProductNonStandard的id
                'new_item_id'=> 'required',//supply_item或supply_item_non_standard的id
            )
            );
        $response = array('code' => 0, 'msg' => 'ok','result'=>array('order_id'=>Input::get('order_id')));
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $orders=Orders::find(Input::get('order_id'));
            if(is_null($orders)){
                $response = Lang::get("scs_error.order_notexiet_40000");
                break;
            }
            if($orders->shop_id!=$sc_user->shop_id){
                $response = Lang::get("scs_error.order_note_shop_error_40003");
                break;
            }
            if($orders->order_type==1){
                if(!in_array($orders->status,Orders::$add_product)){//订单状态是正确
                    $response = Lang::get("scs_error.order_status_error_40022");
                    break;
                }
            }else{
                if($orders->status!=1411){//订单状态是正确
                    $response = Lang::get("scs_error.order_status_error_40022");
                    break;
                }
            }
            $op=OrderPay::where("order_id",$orders->order_id)->whereIn("status",array(0,1,5,7))->first();      
            if($op){//订单状态是否为服务结束状态
                $response = Lang::get("scs_error.order_pay_record_40112");
                break;
            }
            $opns=OrderProductNonStandard::where('id',Input::get("order_product_non_standard_id"))->where('status',1)->first();
            if(is_null($opns)||$opns->order_id!=$orders->order_id){
                $response = Lang::get("scs_error.order_product_item_notexit_40011");
                break;
            }
            $order_product=OrderProduct::find($opns->order_product_id);
            if(is_null($order_product)||$order_product->order_id!=$orders->order_id){
                $response = Lang::get("scs_error.order_product_notexit_40006");
                break;
            }
            if($order_product->status!=1){
                $response = Lang::get("scs_error.order_product_status_error_40009");
                break;
            }
            $csi=DataCarStandardInfo::find($orders->car_model_id);
            if(is_null($csi)){
                $response = Lang::get("scs_error.order_car_model_notexit_40002");
                break;
            }
            $si=SupplyItem::find(Input::get("new_item_id"));
            // if(is_null($si)||$si->status!=1){//如果 耗材不存在或者 状态不正确
            //     return Lang::get("scs_error.supply_item_not_exit_41000");
            // }
            // if(Input::get('type')==0){
                $mw=MaintenanceWarehouse::where('item_id',Input::get('new_item_id'))->where('shop_id',$sc_user->shop_id)->first();
                if(!$mw || $opns->num>$mw->number){
                    $response = Lang::get("scs_error.supply_item_low_stocks_40005");
                    break;
                }
                $wmcf=WorkModelCoefficient::where("name",$csi->model_level)->first();
                if(is_null($wmcf)){
                    $response = Lang::get("scs_error.work_mcf_error_10002");
                    break;
                }
                
                // if($opns->type==0){
                $old=SupplyItem::find($opns->item_id);
                // }else{
                //     $old=SupplyItemNonStandard::find($opns->item_id);
                // }
                // if(is_null($si)||$si->status!=1){//如果 耗材不存在或者 状态不正确
                //     $response = Lang::get("scs_error.supply_item_not_exit_41000");
                //     break;
                // }
                if(Orders::isSale($si->id,0)){
                    $response = Lang::get("scs_error.supply_error_10011");
                    break;
                }
                if($old->supply_classification_id!=$si->supply_classification_id){
                    $response = Lang::get("scs_error.supply_subject_error_41002");
                    break;
                }
                // $spi=SupplyProductItem::where("car_model_id",$csi->id)->where("supply_item_id",$si->id)->where("status",1)->first();
                // if(is_null($spi)){
                //     $response = Lang::get("scs_error.supply_item_car_model_error_41001");
                //     break;
                // }

                // $ss=SupplySeries::find($si->series_id);
                $moo=MaintenanceOutOrder::where("product_type","non_standard")->where("product_item_id",$opns->id)->whereIn("status",array(0,1,2))->first();
                if($moo){//如果存在 备货中或者 等待领料的 出库申请 已经领料的 不允许修改
                    $response = Lang::get("scs_error.order_product_item_change_error_40012");
                    break;
                }

                if($si->type==1||PriceBargaining::ischange($si->id,$orders->shop_id)==1){//如果能编辑价格
                    $c_amount=Input::get("amount")*100;
                    $max=MaintenanceStorageItem::where('item_id',Input::get('new_item_id'))->where('type',1)->where('current_number','>',0)->where('status',1)->max('tax_purchase_price');
                    if($c_amount < $max){
                        $response = Lang::get("scs_error.data_price_error_61018");
                        break;
                    }
                }else{  
                    //更换耗材的加价系数
                    $wpc=WorkPartsCoefficient::where("car_model_name",$csi->model_level)->where("supply_brand_id",$si->brand_id)->where("supply_subject_id",$si->supply_classification_id)->where("status",1)->first();
                    $wmcf->supply_coefficient = null;
                    if (!empty($wpc)) {
                        $wpc_city=WorkPartsCoefficientCity::where('city_id',$sc_user->shop->city_id)->where('coefficient_id',$wpc->id)->where('status',1)->first();
                        $wmcf->supply_coefficient=isset($wpc_city->coefficient) ? $wpc_city->coefficient : null; //如果有城市系数，优先使用。
                    }
                    if ($wmcf->supply_coefficient == null){ //如果是0，说明没有赋值
                        $wmcf->supply_coefficient=isset($wpc->coefficient) ? $wpc->coefficient : 1;
                    }
                    //更换多城市价格
                    // $sip=SupplyItemPrice::where("item_id",$si->id)->where("city_id",$sc_user->shop->city_id)->first();
                    // if($sip){
                    //     $si->amount=$sip->price;
                    // }        
                    $sip=SupplyCityPrice::where("supply_id",$si->id)->where("city_id",$sc_user->shop->city_id)->where("status",1)->first();
                    if($sip){
                        $si->amount=$sip->price;
                    }else{
                        $ss_temp=SupplySub::where("supply_id",$si->id)->where("status",1)->first();
                        $si->amount=isset($ss_temp)?$ss_temp->usual_price:0;
                    }        
                    $c_amount=Common::upFow($si->amount*$wmcf->supply_coefficient);
                }
                if($si->type!=$opns->type||$opns->item_id!=$si->id){//说明更换了耗材 才进这些判断
                    if($opns->type==0){//说明原来 是标准耗材切 更换了耗材
                        OrderSmyFilling::where("order_id",$orders->order_id)->where("product_item_id",$opns->id)->where("product_type","non_standard")->update(array("status"=>0));//取消原来的的耗材的添注记录
                    }
                    //判断特殊油品
                    if(in_array($si->id,Config::get("smy.item_id"))){//如果新耗材是特殊油品
                        OrderSmyFilling::saveosf($orders->shop_id,$si->id,"non_standard",$opns->id,$orders->order_id);
                    } 
                }
                
                
                $opr=new OrderProductRecord();
                $opr->order_id=$orders->order_id;
                $opr->product_type='non_standard';
                $opr->operation_type='update';
                $opr->num=$opns->num;
                $opr->operation_grade='二级';
                $opr->user_id=$sc_user->id;
                $opr->user_type='sc';
                $opr->operation_id=$opns->id;
                $opr->name=$opns->name;
                $opr->amount=$opns->amount;
                $opr->save();

                $item_info=SupplyItem::getCacheItemInfo($si->id);
                $opns->item_id=Input::get('new_item_id');
                $opns->name=$item_info->name;
                $opns->amount=$c_amount;
                $opns->type=$si->type;
                $opns->unit=$item_info->unit?$item_info->unit:'';
                $opns->discount=1;
                $opns->save();
                
                //订单应付金额及优惠信息将重新计算，废弃原有再优惠信息上加减
                Orders::calculate(Input::get('order_id'));
                
            // }else{
            //     $mw=MaintenanceWarehouse::where('item_id',Input::get('new_item_id'))->where('shop_id',$sc_user->shop_id)->where('item_type',1)->first();
            //     if(!$mw || $opns->num>$mw->number){
            //         $response = Lang::get("scs_error.supply_item_low_stocks_40005");
            //         break;
            //     }
            //     $max=MaintenanceStorageItem::where('item_id',Input::get('new_item_id'))->where('type',1)->where('item_type',1)->where('current_number','>',0)->where('status',1)->max('tax_purchase_price');
            //     if(Input::get('amount')*100 < $max){
            //         $response = Lang::get("scs_error.data_price_error_61018");
            //         break;
            //     }
            //     $sins=SupplyItemNonStandard::find(Input::get("new_item_id"));
            //     $sins->amount=Input::get("amount")*100;//如果是非标的 更新非标为传过来的价格
            //     if($opns->type==0){
            //         $old=SupplyItem::find($opns->item_id);
            //     }else{
            //         $old=SupplyItemNonStandard::find($opns->item_id);
            //     }
            //     if(is_null($sins)||$sins->status!=1){//如果 耗材不存在或者 状态不正确
            //         $response = Lang::get("scs_error.supply_item_not_exit_41000");
            //         break;
            //     }
            //     if(Orders::isSale($sins->id,1)){
            //         $response = Lang::get("scs_error.supply_error_10011");
            //         break;
            //     }
            //     if($old->subject!=$sins->subject){
            //         $response = Lang::get("scs_error.supply_subject_error_41002");
            //         break;
            //     }
            //     // if($sins->id==$opns->item_id){//如果没有更换耗材
            //     //     $response = array('code' => 0, 'msg' => 'ok', 'result' => array("order_id"=>$order_product->order_id,"order_product_amount"=>$order_product->amount,"order_amount"=>$orders->amount));
            //     //     break;
            //     // }

            //     $moo=MaintenanceOutOrder::where("product_type","non_standard")->where("product_item_id",$opns->id)->whereIn("status",array(0,1,2))->first();
            //     if($moo){//如果存在 备货中或者 等待领料的 出库申请 已经领料的 不允许修改
            //         $response =  Lang::get("scs_error.order_product_item_change_error_40012");
            //         break;
            //     }
            //     if($opns->type==0){//说明原来 是标准耗材切 更换了耗材
            //         OrderSmyFilling::where("order_id",$orders->order_id)->where("product_item_id",$opns->id)->where("product_type","non_standard")->update(array("status"=>0));//取消原来的的耗材的添注记录
            //     }

            //     $opr=new OrderProductRecord();
            //     $opr->order_id=$orders->order_id;
            //     $opr->product_type='non_standard';
            //     $opr->operation_type='update';
            //     $opr->num=$opns->num;
            //     $opr->operation_grade='二级';
            //     $opr->user_id=$sc_user->id;
            //     $opr->user_type='sc';
            //     $opr->operation_id=$opns->id;
            //     $opr->name=$opns->name;
            //     $opr->amount=$opns->amount;
            //     $opr->save();


            //     $opns->name=$sins->series_name." ".$sins->model;
            //     $opns->item_id=Input::get('new_item_id');
            //     $opns->amount=$sins->amount;
            //     $opns->type=Input::get('type');
            //     $opns->unit=$sins->unit;
            //     $opns->discount=1;
            //     $opns->save();

            //    //订单应付金额及优惠信息将重新计算，废弃原有再优惠信息上加减
            //     Orders::calculate(Input::get('order_id'));                
            // }
            Coupons::check_coupons(Input::get('order_id'));
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "changeNonStandardItem", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /**
     * @Author:      zwh
     * @DateTime:    2016-2-24 14:01:52
     * @Description: 用于修改工时费
     */
    public function updateWorkHours(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'order_id' => 'required',
                'item_id'=> 'required',//order_product_non_standard的id
                'amount' => 'required|numeric'
            )
            );
        $response = array('code' => 0, 'msg' => 'ok','result'=>array('order_id'=>Input::get('order_id')));
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $orders=Orders::find(Input::get('order_id'));
            if(is_null($orders)){
                $response = Lang::get("scs_error.order_notexiet_40000");
                break;
            }
            if($orders->shop_id!=$sc_user->shop_id){
                $response = Lang::get("scs_error.order_note_shop_error_40003");
                break;
            }
            if($orders->order_type==1){
                if(!in_array($orders->status,Orders::$add_product)){//订单状态是正确
                    $response = Lang::get("scs_error.order_status_error_40022");
                    break;
                }
            }else{
                if($orders->status!=1411){//订单状态是正确
                    $response = Lang::get("scs_error.order_status_error_40022");
                    break;
                }
            }
            $op=OrderPay::where("order_id",$orders->order_id)->whereIn("status",array(0,1,5,7))->first();      
            if($op){//订单状态是否为服务结束状态
                $response = Lang::get("scs_error.order_pay_record_40112");
                break;
            }
            if($orders->order_type==1){
                $csi=DataCarStandardInfo::find($orders->car_model_id);
                if(is_null($csi)){//只进行 车型存在 不对车型状态进行祥判断
                    $response = Lang::get("scs_error.order_car_model_notexit_40002");
                    break;
                }
            }
            $opns=OrderProductNonStandard::where('id',Input::get('item_id'))->where('status',1)->first();
            $op=OrderProduct::find($opns->order_product_id);

            if($opns->order_id!=Input::get('order_id')){
                $response = Lang::get("scs_error.supply_subject_error_41003");
                break;
            }

            $opr=new OrderProductRecord();
            $opr->order_id=$orders->order_id;
            $opr->product_type='non_standard';
            $opr->operation_type='update';
            $opr->num=0;
            $opr->operation_grade='二级';
            $opr->user_id=$sc_user->id;
            $opr->user_type='sc';
            $opr->operation_id=$op->id;
            $opr->name=$opns->name;
            $opr->amount=$opns->amount;
            $opr->save();

            $opns->amount=Input::get('amount')*100;
            $opns->save();
            
            //订单应付金额及优惠信息将重新计算，废弃原有再优惠信息上加减
            Orders::calculate(Input::get('order_id'));
            Coupons::check_coupons(Input::get('order_id'));
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("order_id"=>Input::get('order_id')));
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "addService", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /**
     * @Author:      zwh
     * @DateTime:    2016-2-25 10:06:16
     * @Description: 订单添加配件列表(搜索条件为品类与关键字)
     */
    public function partList(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'order_id' => 'required',
            )
            );
        $response = array('code' => 0, 'msg' => 'ok','result'=>array('order_id'=>Input::get('order_id')));
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $orders=Orders::find(Input::get('order_id'));
            if(is_null($orders)){
                $response = Lang::get("scs_error.order_notexiet_40000");
                break;
            }
            if($orders->shop_id!=$sc_user->shop_id){
                $response = Lang::get("scs_error.order_note_shop_error_40003");
                break;
            }
            $csi=DataCarStandardInfo::find($orders->car_model_id);
            if(is_null($csi)){//只进行 车型存在 不对车型状态进行祥判断
                $response = Lang::get("scs_error.order_car_model_notexit_40002");
                break;
            }
            $si_sb = DB::table('supply_info2')->distinct('brand_name')->select('brand_name')->get();
            $snsi_sb = DB::table('supply_non_standard_info')->distinct('brand_name')->select('brand_name')->get();
            //标准配件列表
            $sql="select si.id,si.subject,si.s_name,si.model,si.amount,si.brand_name,si.se_name,mw.number from supply_info2 as si
                Left Join supply_product_item spi on spi.supply_item_id=si.id
                Left Join (select item_type,item_id,shop_id,number from maintenance_warehouse where item_type=0 and shop_id=".$sc_user->shop_id.") mw on mw.item_id=si.id
                where car_model_id=".$orders->car_model_id." and si.status=1 and spi.status=1";
            $sql2="select si.id,si.subject,si.s_name,si.model,si.amount,si.brand_name,si.se_name,mw.number from supply_info2 as si
                Left Join (select item_type,item_id,shop_id,number from maintenance_warehouse where item_type=0 and shop_id=".$sc_user->shop_id.") mw on mw.item_id=si.id
                where si.status=1 ";
            if(Input::get('keywords')){
                $sql.=" and supply_info like '%".Input::get('keywords')."%'";
                $sql2.=" and supply_info like '%".Input::get('keywords')."%'";

            }
            if(Input::get('subject')){
                $sql.=" and subject = ".Input::get('subject');
                $sql2.=" and subject = ".Input::get('subject');

            }
            if(Input::get('brand_name')){
                $sql.=" and brand_name LIKE '%".Input::get('brand_name')."%'";
                $sql2.=" and brand_name LIKE '%".Input::get('brand_name')."%'";

            }
            $arr=DB::select($sql);

            //标准配件分为推荐和所有标准配件
            $temp='';
            $temp1=array();
            foreach($arr as $key=>$a){
                if($key+1==count($arr)){
                    $temp.=$a->id;
                }else{
                    $temp.=$a->id.',';
                }

            }
            $sql2.=" and si.id not in(".$temp.")";
            $arr2=DB::select($sql2);
            foreach($arr as $key=>$v){
                $arr[$key]->recommend=1;
                $temp1[]=$arr[$key];
            }
            foreach($arr2 as $key2=>$v2){
                $temp1[]=$arr2[$key2];
            }
            //非标产品列表
            $sql1="select id,s_name,subject,model,amount,brand_name,series_name,number,code,old_code,retrieval_code from supply_non_standard_info left Join (select item_type,item_id,shop_id,number from maintenance_warehouse where item_type=1 and shop_id=".$sc_user->shop_id.") mw on mw.item_id=supply_non_standard_info.id where 1=1 ";
            if(Input::get('keywords')){
                $sql1.=" and supply_non_standard_info LIKE '%".Input::get('keywords')."%'";
            }
            if(Input::get('subject')){
                $sql1.=" and subject = ".Input::get('subject');
            }
            if(Input::get('brand_name')){
                $sql1.=" and brand_name LIKE '%".Input::get('brand_name')."%'";

            }
            $arr1=DB::select($sql1);
            $subjects=DB::table('supply_subject')->select('id','name')->get();
            $result=array('si'=>$temp1,'snsi'=>$arr1,'subjects'=>$subjects,'si_sb'=>$si_sb,'snsi_sb'=>$snsi_sb);
            $response['result']=$result;
        }while(false);
        // Log::info("info", array("system" => "scs" ,"event" => "addService", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }



    /**
     * @Author:      lyt
     * @DateTime:    2016-04-20 09:24:43
     * @Description: 根据订单查询 匹配的耗材  替代上面的 (partList 订单添加配件列表(搜索条件为品类与关键字)) 方法
     */
    public function supply_search(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'order_id' => 'required',
            )
            );
        $response = array('code' => 0, 'msg' => 'ok','result'=>array('order_id'=>Input::get('order_id')));
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            // $time=time();
            $orders=Orders::find(Input::get('order_id'));
            if(is_null($orders)){
                $response = Lang::get("scs_error.order_notexiet_40000");
                break;
            }
            if($orders->shop_id!=$sc_user->shop_id){
                $response = Lang::get("scs_error.order_note_shop_error_40003");
                break;
            }
            $car_retrieval_code=Input::get("car_retrieval_code");
            $type=Input::get("type");
            $search_retrieval_code=Input::get("retrieval_code");
        
            $car_str=Input::get("car_str");
            if($type||$search_retrieval_code||$car_str){
                // $non_ids=SupplyItemNonStandard::retrievalCode($sc_user->shop_id,$car_retrieval_code,$type,$search_retrieval_code,$car_str);//获得非标的耗材id范围
                $si_ids=SupplyItem::retrievalCode($car_retrieval_code,$type,$search_retrieval_code,$car_str);//获得标准的耗材id范围
            }
            // else{
            //     $response = Lang::get("scs_error.supply_item_searce_args_not_exit_41010");
            //     break;
            // }
            if(isset($si_ids)&&sizeof($si_ids)>5000){
                $response = Lang::get("scs_error.supply_item_searce_args_not_exit_41011");
                break;
            }
            // $time2=time();
            // Log::info($time2-$time);
            $si_sb = DB::table('supply_item')
            ->leftJoin('anhui_data.supply_brand',"supply_brand.id","=","supply_item.brand_id")
            ->distinct('supply_brand.brand_name')->select('supply_brand.brand_name');   
            if(isset($si_ids)){
                $si_sb =$si_sb->whereIn("supply_item.id",$si_ids);
            }
            $si_sb = $si_sb->get();
            // $time3=time();
            // Log::info($time3-$time2);
            // $snsi_sb = DB::table('supply_item_non_standard')->distinct('brand_name')->select('brand_name');
            // if(isset($non_ids)){
            //     $snsi_sb =$snsi_sb->whereIn("id",$non_ids);
            // }
            // $snsi_sb = $snsi_sb->get();

            //标准配件列表
            $sql="select si.id,si.type,mw.number,1 as  recommend,spi.isdefualt from supply_item as si
                Left Join anhui_data.supply_product_item spi on spi.supply_item_id=si.id
                Join (select item_type,item_id,shop_id,number from maintenance_warehouse where shop_id=".$sc_user->shop_id." and number>0) mw on mw.item_id=si.id
                where spi.car_model_id=".$orders->car_model_id."  and spi.status=1  ";
            $sql2="select si.id,si.type,mw.number,0 as  recommend,0 as isdefualt from supply_item as si
                Join (select item_type,item_id,shop_id,number from maintenance_warehouse where shop_id=".$sc_user->shop_id." and number>0 ) mw on mw.item_id=si.id
                where 1=1 ";

            if(Input::get('subject')){
                $sql.=" and supply_classification_id = ".Input::get('subject');
                $sql2.=" and supply_classification_id = ".Input::get('subject');
            }
            if(Input::get('brand_name')){
                $sql.=" and si.brand_name like '%".Input::get('brand_name')."%'";
                $sql2.=" and si.brand_name like '%".Input::get('brand_name')."%'";
            }
            if(isset($si_ids)){
                $si_ids[]=0;
                $sql.=" and si.id in (".implode(",",$si_ids).")";
            }
            $arr=DB::select($sql);//查询 匹配的标准配件
            // $time4=time();
            // Log::info($time4-$time3);
            //标准配件分为推荐和所有标准配件
            $pipei_id=array();

            //所有配件中取出推荐配件（去重）
            foreach($arr as $key=>$a){
                $pipei_id[]=$a->id;
            }
            if(isset($si_ids)){
                $temp_ids=array_diff($si_ids, $pipei_id);
                $temp_ids[]=0;
                $sql2.=" and si.id in (".implode(",",$temp_ids).")";
            }else{
                if(sizeof($pipei_id) >= 1){
                    $sql2.=" and si.id not in(".implode(",",$pipei_id).")";
                }
            }
            $arr2=DB::select($sql2);//查询 所有的标准配件
            // $time5=time();
            // Log::info($time5-$time4);
            $temp1=array_merge($arr,$arr2);
            // $time6=time();
            // Log::info($time6-$time5);
            //非标产品列表
            // $sql1="select id,number from supply_item_non_standard as sion left Join (select item_type,item_id,shop_id,number from maintenance_warehouse where item_type=1 and shop_id=".$sc_user->shop_id.") mw on mw.item_id=sion.id where mw.number>0 ";
            // if(isset($non_ids)){
            //     $non_ids[]=0;
            //     $sql1.=" and sion.id in (".implode(",",$non_ids).")";
            // }
            // $arr1=DB::select($sql1);            
            $csi=DataCarModel::find($orders->car_model_id); 
            // $tuijian=SupplyRecommend::getRecommendByCarModel($csi);

            $finally=$recommend=$isdefualt=array();

            foreach($temp1 as $t){
                $si=SupplyItem::getCacheItemInfo($t->id);
                $sip=SupplyItemPrice::where("item_id",$si->id)->where("city_id",$orders->city)->first();
                if($sip){
                    $si->amount=$sip->price;
                }
                
                $supply_coefficient = null;
                if($csi){
                    $wpc=WorkPartsCoefficient::where("car_model_name",$csi->model_level)->where("supply_brand_id",$si->brand_id)->where("supply_subject_id",$si->supply_classification_id)->where("status",1)->first();                
                    if (!empty($wpc)) {
                        $wpc_city=WorkPartsCoefficientCity::where('city_id',$sc_user->shop->city_id)->where('coefficient_id',$wpc->id)->where('status',1)->first();
                        $supply_coefficient=isset($wpc_city->coefficient) ? $wpc_city->coefficient : null; //如果有城市系数，优先使用。
                    }
                }                
                if ($supply_coefficient == null){ //如果是null，说明没有赋值
                    $supply_coefficient=isset($wpc->coefficient) ? $wpc->coefficient : 1;
                }
                
                $sip=SupplyCityPrice::where("supply_id",$si->id)->where("city_id",$orders->city)->where("status",1)->first();
                if($sip){
                    $si->amount=$sip->price;
                }else{
                    $ss_temp=SupplySub::where("supply_id",$si->id)->where("status",1)->first();
                    $si->amount=isset($ss_temp)?$ss_temp->usual_price:0;
                }
                // if(in_array($si->id, $tuijian)){
                //     $t->isdefualt=1;
                // }
                $si->amount=$si->amount*$supply_coefficient;

                $item_array=array(
                    "id"=>$t->id,
                    "item_type"=>$t->type,
                    "number"=>$t->number,
                    "recommend"=>$t->recommend,
                    "isdefualt"=>$t->isdefualt,
                    "subject"=>$si->subject,
                    "code"=>$si->code,
                    "old_code"=>$si->old_code,
                    "s_name"=>$si->subject_name,
                    "model"=>$si->model,
                    "amount"=>$si->amount,
                    "brand_name"=>$si->brand_name,
                    "se_name"=>$si->series_name,
                    "scf_id"=>$si->st_classifi_id,
                    "scf_name"=>$si->scf_name,
                    "specification"=>$si->specification,
                    "car_model_comments"=>$si->car_model_comments,
                    "ischange"=>PriceBargaining::ischange($t->id,$orders->shop_id),
                    "item_name"=>$si->name,
                );
                $finally[]=$item_array;
                $recommend[]=$t->recommend;
                $isdefualt[]=$t->isdefualt;
            }
            // $time7=time();
            // Log::info($time7-$time6);
            // foreach($arr1 as $a){
            //     $sins=SupplyItemNonStandard::getCacheItemInfo($a->id);
            //     $a->code=$sins->code;
            //     $a->car_model=$sins->car_model;
            //     $a->subject=$sins->subject;
            //     $a->s_name=$sins->subject_name;
            //     $a->model=$sins->model;
            //     $a->amount=$sins->amount;
            //     $a->brand_name=$sins->brand_name;
            //     $a->series_name=$sins->series_name;
            //     $a->scf_id=$sins->st_classifi_id;
            //     $a->scf_name=$sins->scf_name;
            //     $a->specification=$sins->specification;
            //     $a->old_code=$sins->old_code;
            //     $a->retrieval_code=$sins->retrieval_code;
            // }
            array_multisort($recommend, SORT_DESC, $isdefualt, SORT_DESC, $finally);
            $subjects=SupplyClassification::whereIn("id",Config::get("config.maintenance_classification"))->select('id','name')->get();
            $result=array('si'=>$finally,'snsi'=>array(),'subjects'=>$subjects,'si_sb'=>$si_sb,'snsi_sb'=>array());
            $response['result']=$result;
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "supply_search", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }



    /**
     * @Author:      zwh
     * @DateTime:    2016-2-25 13:54:58
     * @Description: 服务列表
     */
    public function serviceList(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                //'order_id' => 'required',
            )
        );
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }/*
            $orders=Orders::find(Input::get('order_id'));
            if(is_null($orders)){
                $response = Lang::get("scs_error.order_notexiet_40000");
                break;
            }
            if($orders->shop_id!=$sc_user->shop_id){
                $response = Lang::get("scs_error.order_note_shop_error_40003");
                break;
            }
            */
            $service_list=Service::where("level",3)->where('status',1);
            if(Input::get('retrieval_code')){
                   $service_list->where('retrieval_code','like',"%".Input::get('retrieval_code')."%");
            }
            $service_list=$service_list->select('id','retrieval_code','name')->orderBy("id","ASC")->get();
            $response = array('code' => 0, 'msg' => 'ok','result'=>array('service_list'=>$service_list));
        }while(false);
        // Log::info("info", array("system" => "scs" ,"event" => "serviceList", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /**
     * @Author:      zwh
     * @DateTime:    2016-2-25 15:26:40
     * @Description: 用于修改 非标产品的 条目数量
     */
    public function changeNonStandardItemNum(){
        $validator = Validator::make(Input::all(),
            array(
                'token'    => 'required',
                'order_id' => 'required',
                'item_id'=> 'required',//order_product_non_standard的id
                'number'=> 'required|numeric|min:0|not_in:0',
            )
            );
        $response = array('code' => 0, 'msg' => 'ok','result'=>array('order_id'=>Input::get('order_id')));
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $orders=Orders::find(Input::get('order_id'));
            if(is_null($orders)){
                $response = Lang::get("scs_error.order_notexiet_40000");
                break;
            }
            if($orders->shop_id!=$sc_user->shop_id){
                $response = Lang::get("scs_error.order_note_shop_error_40003");
                break;
            }
            if(!in_array($orders->status,Orders::$add_product)){//订单状态是正确
                $response = Lang::get("scs_error.order_status_error_40022");
                break;
            }
            $op=OrderPay::where("order_id",$orders->order_id)->whereIn("status",array(0,1,5,7))->first();      
            if($op){//订单状态是否为服务结束状态
                $response = Lang::get("scs_error.order_pay_record_40112");
                break;
            }
            $opns=OrderProductNonStandard::where('id',Input::get("item_id"))->where('status',1)->first();
            if(is_null($opns)||$opns->order_id!=$orders->order_id){
                $response = Lang::get("scs_error.order_product_item_notexit_40011");
                break;
            }
            if($opns->service_type!=1){
                $response = Lang::get("scs_error.supply_service_type_error_41004");
                break;
            }
            $order_product=OrderProduct::find($opns->order_product_id);
            if(is_null($order_product)||$order_product->order_id!=$orders->order_id){
                $response = Lang::get("scs_error.order_product_notexit_40006");
                break;
            }
            if($order_product->status!=1){
                $response = Lang::get("scs_error.order_product_status_error_40009");
                break;
            }
            $number=Input::get("number");
            $mw=MaintenanceWarehouse::where('item_id',$opns->item_id)->where('shop_id',$sc_user->shop_id)->first();
            if(!$mw || $number > $mw->number){
                $response = Lang::get("scs_error.supply_item_low_stocks_40005");
                break;
            }
            $amount=Input::get("amount")*100;
            if($number==$opns->num&&$amount==$opns->amount){
                $response = array('code' => 0, 'msg' => 'ok', 'result' => array("order_id"=>$order_product->order_id,"order_product_amount"=>$order_product->amount,"order_amount"=>$orders->amount));
                break;
            }

            $response=OrderProductNonStandard::changeProductItemNum(Input::get('order_id'),$opns,$number,$amount,$sc_user->id);
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "changeNonStandardItemNum", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /**
     * @Author:      zwh
     * @DateTime:    2016-5-5 10:31:41
     * @Description: 非标 配件工时打折
     */
    /**
     * @Author:      lyt
     * @DateTime:    2016-05-07 11:30:41
     * @Description: 修改优惠计算  修改工时打折  应付修改
     */
    public function nonStandardDiscount(){
        $validator = Validator::make(Input::all(),
            array(
                'token'    => 'required',
                'order_id' => 'required',
                'order_product_item_id'=> 'required',//order_product_non_standard的id
                'discount'=> 'required|numeric|max:1',
            )
            );
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }

            $discount=Input::get("discount");
            $response=DB::transaction(function () use ($discount,$sc_user) {
                $response = array('code' => 0, 'msg' => 'ok');
                $orders=Orders::where('order_id',Input::get('order_id'))->lockForUpdate()->first();
                if(is_null($orders)){
                    return $response = Lang::get("scs_error.order_notexiet_40000");
                }
                if($orders->shop_id!=$sc_user->shop_id){
                    return $response = Lang::get("scs_error.order_note_shop_error_40003");
                }
                $op=OrderPay::where("order_id",$orders->order_id)->whereIn("status",array(0,1,5,7))->first();      
                if($op){//订单状态是否为服务结束状态
                    $response = Lang::get("scs_error.order_pay_record_40112");
                    return $response;
                }                  
                if(!in_array($orders->status,Orders::$change_price)){//订单状态是正确
                    return $response = Lang::get("scs_error.order_status_error_40022");
                }
                $opns=OrderProductNonStandard::where('id',Input::get("order_product_item_id"))->where('status',1)->lockForUpdate()->first();
                if(is_null($opns)||$opns->order_id!=$orders->order_id){
                    return $response = Lang::get("scs_error.order_product_item_notexit_40011");
                }
                $order_product=OrderProduct::where('id',$opns->order_product_id)->lockForUpdate()->first();
                if(is_null($order_product)||$order_product->order_id!=$orders->order_id){
                    return $response = Lang::get("scs_error.order_product_notexit_40006");
                }
                if($order_product->status!=1){
                    return $response = Lang::get("scs_error.order_product_status_error_40009");
                }
                // $old=OrderPriceChangeRecords::where('order_id',Input::get('order_id'))->sum('amount');
                // $new=OrderPriceChangeRecords::where('order_id',Input::get('order_id'))->sum('modify_amount');
                // if($old != $new){
                //     return $response = Lang::get("scs_error.order_modify_error_40062");
                // }

                // 先将折扣信息保存
                $opns->discount=$discount;
                $opns->save();
                
                //订单应付金额及优惠信息将重新计算，废弃原有再优惠信息上加减
                Orders::calculate(Input::get('order_id'));
                $response['result']=array('price'=>$opns->amount*$discount);
                return $response;
            });
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "non_standard_discount", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /**
     * @Author:      zwh
     * @DateTime:    2016-5-5 10:31:41
     * @Description: 标准 配件工时打折
     */
    /**
     * @Author:      lyt
     * @DateTime:    2016-05-07 11:30:05
     * @Description: 修改优惠计算  修改工时打折  应付修改
     */
    public function discount(){
        $validator = Validator::make(Input::all(),
            array(
                'token'    => 'required',
                'order_id' => 'required',
                'order_product_item_id'=> 'required',//order_product_non_standard的id
                'discount'=> 'required|numeric|max:1',
            )
            );

        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $discount=Input::get("discount");
            $response=DB::transaction(function () use ($discount,$sc_user) {
                $response = array('code' => 0, 'msg' => 'ok');
                $orders=Orders::where('order_id',Input::get('order_id'))->lockForUpdate()->first();
                if(is_null($orders)){
                    return $response = Lang::get("scs_error.order_notexiet_40000");
                }
                if($orders->shop_id!=$sc_user->shop_id){
                    return $response = Lang::get("scs_error.order_note_shop_error_40003");
                }
                $op=OrderPay::where("order_id",$orders->order_id)->whereIn("status",array(0,1,5,7))->first();      
                if($op){//订单状态是否为服务结束状态
                    $response = Lang::get("scs_error.order_pay_record_40112");
                    return $response;
                } 
                if(!in_array($orders->status,Orders::$change_price)){//订单状态是正确
                    return $response = Lang::get("scs_error.order_status_error_40022");
                }
                $opbi=OrderProductBaseItem::where('id',Input::get("order_product_item_id"))->lockForUpdate()->first();
                if(is_null($opbi)||$opbi->order_id!=$orders->order_id){
                    return $response = Lang::get("scs_error.order_product_item_notexit_40011");
                }
                $order_product=OrderProduct::where('id',$opbi->order_product_package_id)->lockForUpdate()->first();
                if(is_null($order_product)||$order_product->order_id!=$orders->order_id){
                    return $response = Lang::get("scs_error.order_product_notexit_40006");
                }
                if($order_product->status!=1){
                    return $response = Lang::get("scs_error.order_product_status_error_40009");
                }
                if(OrderProduct::isUseCoupon(Input::get('order_id'),$order_product->id)){
                    return $response = Lang::get("scs_error.order_coupon_error_40072");
                }
                // $old=OrderPriceChangeRecords::where('order_id',Input::get('order_id'))->sum('amount');
                // $new=OrderPriceChangeRecords::where('order_id',Input::get('order_id'))->sum('modify_amount');
                // if($old != $new){
                //     return $response = Lang::get("scs_error.order_modify_error_40062");
                // }
                
                // 先将折扣信息保存
                $opbi->discount=$discount;
                $opbi->save();
                
                //订单应付金额及优惠信息将重新计算，废弃原有再优惠信息上加减
                Orders::calculate(Input::get('order_id'));
                $response['result']=array('price'=>$opbi->amount*$discount);
                return $response;
            });
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "discount", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     * @Author:      zwh
     * @DateTime:    2016-6-13 14:11:20
     * @Description: 批量配件工时打折
     */
    public function discounts(){
        $validator = Validator::make(Input::all(),
            array(
                'token'    => 'required',
                'order_id' => 'required',
                'discount'=> 'required|numeric|max:1',
            )
        );
    
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $discount=Input::get("discount");
            $response=DB::transaction(function () use ($discount,$sc_user) {
                $response = array('code' => 0, 'msg' => 'ok','result'=>array('order_id'=>Input::get('order_id')));
                $orders=Orders::where('order_id',Input::get('order_id'))->lockForUpdate()->first();
                if(is_null($orders)){
                    return $response = Lang::get("scs_error.order_notexiet_40000");
                }
                if($orders->shop_id!=$sc_user->shop_id){
                    return $response = Lang::get("scs_error.order_note_shop_error_40003");
                }
                $op=OrderPay::where("order_id",$orders->order_id)->whereIn("status",array(0,1,5,7))->first();      
                if($op){//订单状态是否为服务结束状态
                    $response = Lang::get("scs_error.order_pay_record_40112");
                    return $response;
                }  
                if(!in_array($orders->status,Orders::$change_price)){//订单状态是正确
                    return $response = Lang::get("scs_error.order_status_error_40022");
                }
                // $old=OrderPriceChangeRecords::where('order_id',Input::get('order_id'))->sum('amount');
                // $new=OrderPriceChangeRecords::where('order_id',Input::get('order_id'))->sum('modify_amount');
                // if($old != $new){
                //     return $response = Lang::get("scs_error.order_modify_error_40062");
                // }
                $order_product=OrderProduct::where('order_id',Input::get('order_id'))->where('status',1)->lockForUpdate()->get();
                $discount_fail=array();
                foreach($order_product as $op){
                    if($op->product_type=='base'){
                        if(OrderProduct::isUseCoupon(Input::get('order_id'),$op->id)){
                            $fail=array('pack_id'=>$op->product_id,'pack_name'=>$op->product_name);
                            $discount_fail[]=$fail;
                            continue;
                        }
                        $opbi=OrderProductBaseItem::where('order_product_package_id',$op->id)->lockForUpdate()->get();
                        foreach($opbi as $_opbi){
                            $_opbi->discount=$discount;
                            $_opbi->save();
                        }
                    }
                    if($op->product_type=='non_standard'){
                        $opns=OrderProductNonStandard::where('order_product_id',$op->id)->where('status',1)->lockForUpdate()->get();
                        foreach($opns as $_opns){
                            $_opns->discount=$discount;
                            $_opns->save();
                        }
                    }
                    
                    
                }
                $orders->discount_rate=$discount;
                $orders->save();
                
                //订单应付金额及优惠信息将重新计算，废弃原有累计加减算法
                Orders::calculate(Input::get('order_id'));
                $response['discount_fail']=$discount_fail;
                return $response;
            });
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "discounts", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    /**
     * @Author:      zwh
     * @DateTime:    2016-9-13 15:49:41
     * @Description: 核销列表
     */
    public function verification(){
        $validator = Validator::make(Input::all(),
            array(
                'token'    => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            //未核销金额
            $not_verify_amount=OrderPayRecord::leftJoin('orders','orders.order_id','=','order_pay_record.order_id')
                ->leftJoin('users','users.id','=','orders.user_id')
                ->where('order_pay_record.pay_type',6)
                ->where('orders.verify_status',0)
                ->where('orders.shop_id',$sc_user->shop_id)
                ->sum('order_pay_record.amount');
            //已核销金额
            $verify_amount=OrderPayRecord::leftJoin('orders','orders.order_id','=','order_pay_record.order_id')
                ->leftJoin('users','users.id','=','orders.user_id')
                ->where('order_pay_record.pay_type',6)
                ->where('orders.verify_status',1)
                ->where('orders.shop_id',$sc_user->shop_id)
                ->sum('order_pay_record.amount');
            //核销列表
            $opr=OrderPayRecord::leftJoin('orders','orders.order_id','=','order_pay_record.order_id')
                ->leftJoin('users','users.id','=','orders.user_id')
                ->leftJoin('maintenance_shops','maintenance_shops.id','=','orders.shop_id')
                ->leftJoin('return_order','return_order.order_id','=','orders.order_id')
                ->where('order_pay_record.pay_type',6)
                ->where('orders.shop_id',$sc_user->shop_id)
                ->select('order_pay_record.amount','orders.order_id','orders.created_at','orders.pay_time','orders.order_type','orders.car_no','orders.car_model_name','orders.verify_time','orders.verify_status','maintenance_shops.name','return_order.id','return_order.amount as return_amount','users.real_name');
            if(Input::get('order_id')){
                $opr->where('orders.order_id','like',"%".Input::get('order_id')."%");
            }
            if(Input::get('start_time')){
                $start_time=Input::get('start_time');
                $start_time=$start_time.' 00:00:00';
                $opr->where('orders.pay_time','>=',$start_time);
            }
            if(Input::get('end_time')){
                $end_time=Input::get('end_time');
                $end_time=$end_time.' 23:59:59';
                $opr->where('orders.pay_time','<=',$end_time);
            }
            if(Input::get('user_id')){
                $opr->where('orders.user_id',Input::get('user_id'));
            }
            $verify_status=Input::get('verify_status');
            if($verify_status!=""){
                $opr->where('orders.verify_status',$verify_status);
            }
            $opr=$opr->get();
            
            //实际应收
            foreach($opr as $_opr){
                $_opr->actual_amount=$_opr->amount-$_opr->return_amount;
            }
            //企业列表
            $companys=OrderPayRecord::leftJoin('orders','orders.order_id','=','order_pay_record.order_id')
            ->leftJoin('users','users.id','=','orders.user_id')
            ->where('users.type',2)
            ->where('order_pay_record.pay_type',6)
            ->where('orders.shop_id',$sc_user->shop_id)
            ->distinct('orders.user_id')
            ->select('orders.user_id','users.real_name')
            ->get();
            $users=SCUser::where('shop_id',$sc_user->shop_id)->where('status',1)->where('title',1)->select('id','real_name')->get();
            $tmp_arr=array(
                'not_verify_amount'=>$not_verify_amount,
                'verify_amount'=>$verify_amount,
                'orders'=>$opr,
                'company'=>$companys,
                'user'=>$users
            );
            $response['result']=$tmp_arr;
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "verification", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     * @Author:      zwh
     * @DateTime:    2016-9-14 11:13:55
     * @Description: 核销
     */
    public function verify(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'order_ids' => 'required',
            )
        );
        $order_ids=json_decode(Input::get('order_ids'),1);
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.station_args_error_31001");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $verify_status=Orders::whereIn('order_id',$order_ids)->select('verify_status')->get()->toArray();
            $verify_status=array_column($verify_status,'verify_status');
            if(in_array(1,$verify_status)){
                $response = Lang::get("scs_error.order_verify_error_40067");
                $response["result"]=array("存在已核销订单");
                break;
            }
            if(Input::get('type')==1){
                $sc=SCUser::find(Input::get('id'));
                $area="010";
                $phone=$sc->phone;
                //判断验证码是否存在
                $record = UserCheckCodeUpgrade::where('business_id',$order_ids[0])->where("business_type","verification")->where("phone",$phone)->first();
                if(is_null($record)){ //没有记录
                    $response = Lang::get("error.user_login_checkcode_null_1012");
                    break;
                }
                //校验是否超过时限
                if( time() > Common::datetime2Num($record->out_time_at) ){
                    $response = Lang::get("error.user_login_checkcode_timeout_1013");
                    break;
                }
            
                //校验验证码是否匹配
                if($record->check_code != Input::get('code')){
                    $response = Lang::get("error.user_login_checkcode_error_1014");
                    break;
                }
            }else{
                $sc=SCUser::where('user_name',Input::get('account'))->where('password',strtoupper(md5(Input::get('passwd'))))->where('status',1)->first();
                if(is_null($sc)){
                    $response = Lang::get("scs_error.scs_user_not_exiet21009");
                    break;
                }
                if($sc->title!=1){
                    $response = Lang::get("scs_error.login_user_error_21016");
                    break;
                }
            }
            $response=DB::transaction(function () use ($order_ids) {
                foreach($order_ids as $order_id){
                    $order=Orders::find($order_id);
                    $order->verify_time=date('Y-m-d H:i:s',time());
                    $order->verify_status=1;
                    $order->save();
                }
                return  array('code' => 0, 'msg' => 'ok', 'result' => '');
            });
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "verify", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     * @Author:      zwh
     * @DateTime:    2016-9-14 11:13:55
     * @Description: 取消核销
     */
    public function cancelVerify(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'order_ids' => 'required',
            )
        );
        $order_ids=json_decode(Input::get('order_ids'),1);
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.station_args_error_31001");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $response=DB::transaction(function () use ($order_ids) {
                foreach($order_ids as $order_id){
                    $order=Orders::find($order_id);
                    if($order->verify_status==0){//如果 取消核销 报错
                        DB::rollback();
                        $response = Lang::get("scs_error.order_verify_error_40068");
                        $response["result"]=array($order_id."未核销");
                        return $response;
                    }
                    $order->verify_time=null;
                    $order->verify_status=0;
                    $order->save();
                }
                return  array('code' => 0, 'msg' => 'ok', 'result' => '');
            });
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "cancelVerify", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     * @Author:      zwh
     * @DateTime:    2016-9-23 17:37:39
     * @Description: 核销前判断
     */
    public function verifyBefore(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'order_ids' => 'required',
            )
        );
        $order_ids=json_decode(Input::get('order_ids'),1);
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.station_args_error_31001");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $verify_status=Orders::whereIn('order_id',$order_ids)->select('verify_status')->get()->toArray();
            $verify_status=array_column($verify_status,'verify_status');
            if(in_array(1,$verify_status)){//如果 取消核销 报错
                $response = Lang::get("scs_error.order_verify_error_40067");
                $response["result"]=array("存在已核销订单");
                break;
            }
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "cancelVerify", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     * @Author:      zwh
     * @DateTime:    2016-8-3 18:47:58
     * @Description: 发短信
     */
    public function verifyMessage(){
        $validator = Validator::make(Input::all(),
            array(
                'token'    => 'required',
                "id"=>'required',
                "order_ids"=>'required'
            )
        );
        $response = array('code' => 0, 'msg' => 'ok','result'=>array('order_id'=>Input::get('order_id')));
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $order_ids=json_decode(Input::get('order_ids'),1);
            $sc=SCUser::find(Input::get('id'));
            $phone=$sc->phone;
            $area='';
            $time_out_default = Config::get("user.time_out_default");
    
            //检查手机号是否下发验证码
            $record = UserCheckCodeUpgrade::whereIn('business_id',$order_ids)->where("business_type","verification")->orderBy('out_time_at')->where("phone",$phone)->get();
            if(!is_null($record)){ //有记录
                //判断是否超时
                if( time() < Common::datetime2Num($record[0]->out_time_at) ){ //没有超过时限
                    try {
                        $sms_send_record_id = Sms::send_message($area,$phone,'您好：'.$sc_user->shop->name.'，申请核销业务，您的授权码为'.$record[0]->check_code);
                    } catch (Exception $e) {
                        Log::error("error", array("system" => "scs" ,"event" => "sendMessage", 'input' =>Input::all() ,"exception" => $e));
                        $response = Lang::get("error.user_sms_check_code_send_error_1003");
                        break;
                    }
                    $response = array(
                        'code' => 0,
                        'msg' => 'ok',
                        'result' => array(
                            'out_time' => Common::datetime2Num($record[0]->out_time_at) - time(),
                    ));
                    break;
                }else{ //超过限时
                    UserCheckCodeUpgrade::whereIn('business_id',$order_ids)->where("business_type","verification")->orderBy('out_time_at')->where("phone",$phone)->delete();
                }
            }
            //超过时限和没有记录
            //生成验证码
            $check_code = Common::generateCode();
            //调用短信网关发送短信
            try {
                $sms_send_record_id = Sms::send_message($area,$phone,'您好：'.$sc_user->shop->name.'，申请核销业务，您的授权码为'.$check_code);
            } catch (Exception $e) {
                Log::error("error", array("system" => "scs" ,"event" => "sendMessage", 'input' =>Input::all() ,"exception" => $e));
                $response = Lang::get("error.user_sms_check_code_send_error_1003");
                break;
            }
            $response=DB::transaction(function () use ($order_ids,$phone,$check_code,$time_out_default,$sms_send_record_id) {
                foreach($order_ids as $order_id){
                    $record = new UserCheckCodeUpgrade;
                    $record->business_type="business_commission";
                    $record->business_id=$order_id;
                    $record->phone=$phone;
                    $record->area="";
                    $record->check_code=$check_code;
                    $record->out_time_at=Common::num2DateTime(time() + $time_out_default);
                    $record->send_id=$sms_send_record_id;
                    $record->save();
                }
        
                //组织返回
                $response = array(
                    'code' => 0,
                    'msg' => 'ok',
                    'result' => array(
                        'out_time' => $time_out_default,
                    ));
                return $response;
            });
    
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "accredit", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     * @Author:      zwh
     * @DateTime:    2016-11-24 14:18:48
     * @Description: 修改优惠券勾选状态
     */
    public function changeCouponStatus(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'order_id' => 'required',
                'status' => 'required',
                'coupon_id' => 'required'
            )
        );
        $order_id=Input::get('order_id');
        $status=Input::get('status');
        $coupon_id=Input::get('coupon_id');
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.station_args_error_31001");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $op=OrderPay::where("order_id",$order_id)->whereIn("status",array(0,1,5,7))->first();      
            if($op){//订单状态是否为服务结束状态
                $response = Lang::get("scs_error.order_pay_record_40112");
                break;
            }  
            $response=Orders::changeCouponStatus($order_id,$status,$coupon_id,$sc_user->id);
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "changeCouponStatus", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /**
     * @Author:      lyt
     * @DateTime:  2017-03-11 13:42:02
     * @Description: 用于订单删除一个优惠券
     */
    public function deleteCoupon(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'order_id' => 'required',
                'coupon_id' => 'required'
            )
        );
        $order_id=Input::get('order_id');
        $coupon_id=Input::get('coupon_id');
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.station_args_error_31001");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $op=OrderPay::where("order_id",$order_id)->whereIn("status",array(0,1,5,7))->first();      
            if($op){//订单状态是否为服务结束状态
                $response = Lang::get("scs_error.order_pay_record_40112");
                break;
            } 
            $response=Orders::deleteCopon($order_id,$coupon_id);
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "deleteCoupon", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     * @Author:      zwh
     * @DateTime:    2016-11-21 14:46:27
     * @Description: 复检前判断
     */
    public function recheckBefore(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'order_id' => 'required',
            )
        );
    
        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("sce_error.login_args_error_1001");
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $order_id=Input::get('order_id');
            $account=Input::get('account');
            $passwd=Input::get('passwd');
            $orders=Orders::find($order_id);
            if(is_null($orders)){
                $response = Lang::get("sce_error.order_notexiet_1012");
                break;
            }
            if($orders->shop_id!=$sc_user->shop_id){
                $response = Lang::get("sce_error.order_note_shop_error_1013");
                break;
            }
            if($orders->status != 1215){
                $response = Lang::get("sce_error.order_status_error_1019");
                break;
            }
            if(!MaintenanceOutOrder::isAllOut($orders->order_id)){//是否有 没有出入库记录的耗材
                $response = Lang::get("scs_error.order_out_return_notexit_40035");
                break;
            }
            if(Orders::isOutReturnOrders($orders->order_id)){//是否有 未完成的出退库 记录
                $response = Lang::get("scs_error.order_out_return_error_40034");
                break;
            }
        } while (false);
        Log::info("info", array("system" => "sce" ,"event" => "recheck", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     * @Author:      zwh
     * @DateTime:    2016-11-21 14:46:27
     * @Description: 复检
     * @link：http://www.activity.com/v1/scs/order/recheck?token=875887b2a901f93106aeccf16fae2f8b&order_id=15300060449174&type=2&account=shiqingqing&passwd=123456
     */
    public function recheck(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'order_id' => 'required',
                'type' => 'required',
                "code"=>'numeric',
            )
        );
    
        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("sce_error.login_args_error_1001");
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $order_id=Input::get('order_id');
            $account=Input::get('account');
            $passwd=Input::get('passwd');
            $orders=Orders::find($order_id);
            if(is_null($orders)){
                $response = Lang::get("sce_error.order_notexiet_1012");
                break;
            }
            if($orders->shop_id!=$sc_user->shop_id){
                $response = Lang::get("sce_error.order_note_shop_error_1013");
                break;
            }
            if($orders->status != 1215){
                $response = Lang::get("sce_error.order_status_error_1019");
                break;
            }
            if(!MaintenanceOutOrder::isAllOut($orders->order_id)){//是否有 没有出入库记录的耗材
                $response = Lang::get("scs_error.order_out_return_notexit_40035");
                break;
            }
            if(Orders::isOutReturnOrders($orders->order_id)){//是否有 未完成的出退库 记录
                $response = Lang::get("scs_error.order_out_return_error_40034");
                break;
            }
            
            if(Input::get('type')==1){
                $me=MaintenanceEngineers::find(Input::get('id'));
                $area="010";
                $phone=$me->phone;
                //判断验证码是否存在
                $record = UserCheckCodeUpgrade::where('business_id',Input::get('order_id'))->where("business_type","recheck")->where("phone",$phone)->first();
                if(is_null($record)){ //没有记录
                    $response = Lang::get("error.user_login_checkcode_null_1012");
                    break;
                }
                //校验是否超过时限
                if( time() > Common::datetime2Num($record->out_time_at) ){
                    $response = Lang::get("error.user_login_checkcode_timeout_1013");
                    break;
                }
            
                //校验验证码是否匹配
                if($record->check_code != Input::get('code')){
                    $response = Lang::get("error.user_login_checkcode_error_1014");
                    break;
                }
            }else{
                $me = MaintenanceEngineers::where('account',$account)
                ->where('passwd',md5($passwd))
                ->where('status',1)
                ->where('type_id',$sc_user->shop_id)
                ->whereIn('title',array(1,2))
                ->first();
                if(is_null($me)){
                    $response = Lang::get("sce_error.user_not_exist_1021");
                    break;
                }
            }
    
            try {
                $orders->status=Config::get('order.engineer_service_end_order_status');
                $orders->end_time=Common::num2DateTime(time());
                $orders->save();

                $order_flows = new OrderFlows;
                $order_flows->order_id = $order_id;
                $order_flows->status = Config::get('order.engineer_service_end_order_status');
                $order_flows->type = 'engineer';
                $order_flows->user_id = $me->id;
                $order_flows->created_at = Common::num2DateTime(time());
                $order_flows->save();

                //清除这个订单的停车场数据
                MaintenancePark::where('order_id',$order_id)->delete();

                $mp = new MaintenancePark();
                $mp->shop_id=$me->type_id;
                $mp->order_id=$order_id;
                $mp->status=1;
                $mp->user_id=$me->id;
                $mp->save();


                //记录车辆进入工位时间（开始时间）
                $station = MaintenanceStationCarStatus::where('order_id',Input::get('order_id'))->first();
                try {
                    $station_start_time = MaintenanceStationDetails::UpdatedDetails(Input::get('order_id'),$me->type_id);
                }catch(Exception $e){
                    Log::error("error", array("system" => "scs" ,"event" => "UpdatedDetails", 'input' =>Input::all() ,"exception" => $e));
                }

//                if(is_null($station_start_time)){
//                    $response = Lang::get("sce_error.station_car_start_time_exiet_1001");
//                    break;
//                }
//                if($station_start_time == '0'){
//                    $response = Lang::get("sce_error.station_car_start_time_exiet_1002");
//                    break;
//                }
//                if($station_start_time == '1'){
//                    $response = Lang::get("sce_error.station_car_start_time_exiet_1003");
//                    break;
//                }
//                if($station_start_time == '3'){
//                    $response = Lang::get("sce_error.work_station_car_no_empty1014");
//                    break;
//                }
//                if($station_start_time == '4'){
//                    $response = Lang::get("sce_error.station_car_start_time_exiet_1004");
//                    break;
//                }
                $mscs=MaintenanceStationCarStatus::where('order_id',Input::get('order_id'))->update(array("car_no"=>"","status"=>0,"car_model_id"=>0,"order_id"=>0,'mileage'=>0,'vin_code'=>'','insurance'=>'','start_off_time'=>''));

                //推送微信信息
                $wechat_user=Users::find($orders->user_id);
                if(isset($wechat_user)&&$wechat_user->openid){
                    $templateId = Config::get('config.scs_order_start_templateId');
                    $url = Config::get('config.redirect_url').'/order/show?is_wash=0&order_id='.$orders->order_id;
                    $data = array(
                        "first"  => "亲爱的车主您好，你的爱车服务进度已更新。",
                        "keyword1" =>  $orders->car_no,
                        "keyword2"   => "保养/维修",
                        "keyword3"   => "服务完成待结算",
                        "remark" => "请点击查看详细检测记录"
                    );
                    try {
                        WechatOauthController::sendMessage($wechat_user->openid, $templateId, $data, $url);
                    }catch(Exception $e){
                        Log::error("error", array("system" => "scs" ,"event" => "sendMessage", 'input' =>Input::all() ,"exception" => $e));
                    }
                }

                $result = array('order_id' => $order_id);
                $response = array('code' => 0, 'msg' => 'ok', 'result' => $result);
            } catch (Exception $e) {
                Log::error("error", array("system" => "sce" ,"event" => "order_recheck", 'input' =>Input::all() ,"exception" => $e));
                $response = Lang::get("sce_error.order_cancel_error_1008");
                break;
            }
        } while (false);
        Log::info("info", array("system" => "sce" ,"event" => "recheck", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     * @Author:      zwh
     * @DateTime:    2016-11-21 15:20:47
     * @Description: 发短信
     */
    public function sendMessage(){
        $validator = Validator::make(Input::all(),
            array(
                'token'    => 'required',
                "id"=>'required',
                "order_id"=>'required'
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $id=Input::get('id');
            $order_id=Input::get('order_id');
            $me=MaintenanceEngineers::find(Input::get('id'));
            $phone=$me->phone;
            $area='';
            $time_out_default = Config::get("user.time_out_default");

            //检查手机号是否下发验证码
            $record = UserCheckCodeUpgrade::where('business_id',$order_id)->where("business_type","recheck")->where("phone",$phone)->first();
            if($record){ //有记录
                //判断是否超时
                if( time() < Common::datetime2Num($record->out_time_at) ){ //没有超过时限
                    try {
                        $sms_send_record_id = Sms::send_message($area,$phone,'您好：'.$sc_user->shop->name.'，复检业务，您的授权码为'.$record->check_code);
                    } catch (Exception $e) {
                        Log::error("error", array("system" => "scs" ,"event" => "sendMessage", 'input' =>Input::all() ,"exception" => $e));
                        $response = Lang::get("error.user_sms_check_code_send_error_1003");
                        break;
                    }
                    $response = array(
                        'code' => 0,
                        'msg' => 'ok',
                        'result' => array(
                            'out_time' => Common::datetime2Num($record->out_time_at) - time(),
                        ));
                    break;
                }else{ //超过限时
                    UserCheckCodeUpgrade::where('business_id',$order_id)->where("business_type","recheck")->where("phone",$phone)->delete();
                }
            }
            //超过时限和没有记录
            //生成验证码
            $check_code = Common::generateCode();
            //调用短信网关发送短信
            try {
                $sms_send_record_id = Sms::send_message($area,$phone,'您好：'.$me->name.'，复检业务，您的授权码为'.$check_code);
            } catch (Exception $e) {
                Log::error("error", array("system" => "scs" ,"event" => "sendMessage", 'input' =>Input::all() ,"exception" => $e));
                $response = Lang::get("error.user_sms_check_code_send_error_1003");
                break;
            }
            $record = new UserCheckCodeUpgrade;
            $record->business_type="recheck";
            $record->business_id=$order_id;
            $record->phone=$phone;
            $record->area="";
            $record->check_code=$check_code;
            $record->out_time_at=Common::num2DateTime(time() + $time_out_default);
            $record->send_id=$sms_send_record_id;
            $record->save();
            
            $response['result'] = array('out_time' => $time_out_default);
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "sendMessage", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    /**
     * @Author:      zwh
     * @DateTime:    2016-11-24 17:05:43
     * @Description: 技师列表
     */
    public function engineerList(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("sce_error.login_args_error_1001");
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $mes = MaintenanceEngineers::where('status',1)->where('type','shop')->where('type_id',$sc_user->shop_id)->whereIn('title',array(1,2))->select('id','name')->get();
            $response['result']=array('mes'=>$mes);
        } while (false);
        Log::info("info", array("system" => "sce" ,"event" => "engineerList", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }


   /**
    * @Author:      lyt
    * @DateTime:  2017-04-11 14:10:58
    * @Description: 添加判断 能否进入判断更换窗体
    */
    public function changeBaseProductItemBefore(){
        $validator = Validator::make(Input::all(),
            array(
                'token'    => 'required',
                'order_id' => 'required',
                'order_product_base_item_id'=> 'required',//订单耗材的id
            )
        );
        $response = array('code' => 0, 'msg' => 'ok','result'=>array('order_id'=>Input::get('order_id')));
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $orders=Orders::find(Input::get('order_id'));
            if(is_null($orders)){
                $response = Lang::get("scs_error.order_notexiet_40000");
                break;
            }
            if($orders->shop_id!=$sc_user->shop_id){
                $response = Lang::get("scs_error.order_note_shop_error_40003");
                break;
            }
            if($orders->order_type==1){
                if(!in_array($orders->status,Orders::$add_product)){//订单状态是正确
                    $response = Lang::get("scs_error.order_status_error_40022");
                    break;
                }
            }else{
                if($orders->status!=1411){//订单状态是正确
                    $response = Lang::get("scs_error.order_status_error_40022");
                    break;
                }
            }
            $op=OrderPay::where("order_id",$orders->order_id)->whereIn("status",array(0,1,5,7))->first();      
            if($op){//订单状态是否为服务结束状态
                $response = Lang::get("scs_error.order_pay_record_40112");
                break;
            } 
            $opbi=OrderProductBaseItem::find(Input::get("order_product_base_item_id"));
            if(is_null($opbi)||$opbi->order_id!=$orders->order_id||$opbi->type!=1){
                $response = Lang::get("scs_error.order_product_item_notexit_40011");
                break;
            }
            $order_product=OrderProduct::find($opbi->order_product_package_id);
            if(is_null($order_product)||$order_product->order_id!=$orders->order_id){
                $response = Lang::get("scs_error.order_product_notexit_40006");
                break;
            }
            if($order_product->status!=1){
                $response = Lang::get("scs_error.order_product_status_error_40009");
                break;
            }
            $csi=DataCarStandardInfo::find($orders->car_model_id);
            if(is_null($csi)){
                $response = Lang::get("scs_error.order_car_model_notexit_40002");
                break;
            }
            $wmcf=WorkModelCoefficient::where("name",$csi->model_level)->first();
            if(is_null($wmcf)){
                $response = Lang::get("scs_error.work_mcf_error_10002");
                break;
            }
            $moo=MaintenanceOutOrder::where("product_type","base")->where("product_item_id",$opbi->id)->whereIn("status",array(0,1,2))->first();
            if($moo){//如果存在 备货中或者 等待领料的 出库申请 已经领料的 不允许修改
                $response = Lang::get("scs_error.order_product_item_change_error_40012");
                break;
            }
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "changeBaseProductItemBefore", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }


    /**
     * @Author:      lyt
     * @DateTime:  2017-04-11 14:32:28
     * @Description: 添加判断 能否进入判断更换窗体
     */
    public function changeNonStandardItemBefore(){
        $validator = Validator::make(Input::all(),
            array(
                'token'    => 'required',
                'order_id' => 'required',
                'order_product_non_standard_id'=> 'required',//OrderProductNonStandard的id
            )
        );
        $response = array('code' => 0, 'msg' => 'ok','result'=>array('order_id'=>Input::get('order_id')));
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $orders=Orders::find(Input::get('order_id'));
            if(is_null($orders)){
                $response = Lang::get("scs_error.order_notexiet_40000");
                break;
            }
            if($orders->shop_id!=$sc_user->shop_id){
                $response = Lang::get("scs_error.order_note_shop_error_40003");
                break;
            }
            if($orders->order_type==1){
                if(!in_array($orders->status,Orders::$add_product)){//订单状态是正确
                    $response = Lang::get("scs_error.order_status_error_40022");
                    break;
                }
            }else{
                if($orders->status!=1411){//订单状态是正确
                    $response = Lang::get("scs_error.order_status_error_40022");
                    break;
                }
            }
            $op=OrderPay::where("order_id",$orders->order_id)->whereIn("status",array(0,1,5,7))->first();      
            if($op){//订单状态是否为服务结束状态
                $response = Lang::get("scs_error.order_pay_record_40112");
                break;
            } 
            $opns=OrderProductNonStandard::where('id',Input::get("order_product_non_standard_id"))->where('status',1)->first();
            if(is_null($opns)||$opns->order_id!=$orders->order_id){
                $response = Lang::get("scs_error.order_product_item_notexit_40011");
                break;
            }
            $order_product=OrderProduct::find($opns->order_product_id);
            if(is_null($order_product)||$order_product->order_id!=$orders->order_id){
                $response = Lang::get("scs_error.order_product_notexit_40006");
                break;
            }
            if($order_product->status!=1){
                $response = Lang::get("scs_error.order_product_status_error_40009");
                break;
            }
            // $csi=DataCarStandardInfo::find($orders->car_model_id);
            // if(is_null($csi)){
            //     $response = Lang::get("scs_error.order_car_model_notexit_40002");
            //     break;
            // }               
            // $wmcf=WorkModelCoefficient::where("name",$csi->model_level)->first();
            // if(is_null($wmcf)){
            //     $response = Lang::get("scs_error.work_mcf_error_10002");
            //     break;
            // }
            $moo=MaintenanceOutOrder::where("product_type","non_standard")->where("product_item_id",$opns->id)->whereIn("status",array(0,1,2))->first();
            if($moo){//如果存在 备货中或者 等待领料的 出库申请 已经领料的 不允许修改
                return Lang::get("scs_error.order_product_item_change_error_40012");
            }
                
              
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "changeNonStandardItemBefore", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
}